Android---常用代碼片段整理
1 | 最近有時(shí)間,整理了一下項(xiàng)目中常用到的代碼 |
1、圖片旋轉(zhuǎn):
123456 | Bitmap bitmapOrg = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.moon);Matrix matrix = new Matrix();matrix.postRotate(-90);//旋轉(zhuǎn)的角度Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, bitmapOrg.getWidth(), bitmapOrg.getHeight(), matrix, true);BitmapDrawable bmd = new BitmapDrawable(resizedBitmap); |
2、獲取手機(jī)號碼:
//創(chuàng)建電話管理
TelephonyManager tm = (TelephonyManager)
//與手機(jī)建立連接
activity.getSystemService(Context.TELEPHONY_SERVICE);
//獲取手機(jī)號碼
String phoneId = tm.getLine1Number();
//記得在manifest file中添加
//程序在模擬器上無法實(shí)現(xiàn),必須連接手機(jī)
3.格式化string.xml 中的字符串:
// in strings.xml..
Thanks for visiting %s. You age is %d!
// and in the java code:
String.format(getString(R.string.my_text), "oschina", 33);
4、Android設(shè)置全屏的方法:
A.在java代碼中設(shè)置
/** 全屏設(shè)置,隱藏窗口所有裝飾 */
123 | requestWindowFeature(Window.FEATURE_NO_TITLE);getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); |
B、在AndroidManifest.xml中配置
1234567 | <activity android:name=".Login.NetEdit" android:label="@string/label_net_Edit" android:screenOrientation="portrait" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"><intent-filter> <action android:name="android.intent.Net_Edit" /> <category android:name="android.intent.category.DEFAULT" /></intent-filter></activity> |
5、設(shè)置Activity為Dialog的形式:
在AndroidManifest.xml中配置Activity節(jié)點(diǎn)是配置theme如下:
1 | Android:theme="@android:style/Theme.Dialog" |
6、檢查當(dāng)前網(wǎng)絡(luò)是否連上:
12345 | ConnectivityManager con=(ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE); boolean wifi=con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); boolean internet=con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting(); |
在AndroidManifest.xml 增加權(quán)限:
1 | <uses-permission Android:name="android.permission.ACCESS_NETWORK_STATE" /> |
7、檢測某個(gè)Intent是否有效:
12345678 | public static boolean isIntentAvailable(Context context, String action) { final PackageManager packageManager = context.getPackageManager(); final Intent intent = new Intent(action); List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0;} |
8、android 撥打電話:
1234567 | try { Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:+110")); startActivity(intent);} catch (Exception e) { Log.e("SampleApp", "Failed to invoke call", e);} |
9、android中發(fā)送Email:
1234567 | Intent i = new Intent(Intent.ACTION_SEND); //i.setType("text/plain"); //模擬器請使用這行i.setType("message/rfc822") ; // 真機(jī)上使用這行i.putExtra(Intent.EXTRA_EMAIL, new String[]{"test@gmail.com","test@163.com}); i.putExtra(Intent.EXTRA_SUBJECT,"subject goes here"); i.putExtra(Intent.EXTRA_TEXT,"body goes here"); startActivity(Intent.createChooser(i, "Select email application.")); |
10、Android中打開瀏覽器:**
123 | Intent viewIntent = new Intent("android.intent.action.VIEW",Uri.parse("http://vaiyanzi.cnblogs.com"));startActivity(viewIntent); |
11、Android 獲取設(shè)備唯一標(biāo)識碼:
String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);
12、Android中獲取IP地址:
1 2 3 4 5 6 7 8 9101112131415161718 | public String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e(LOG_TAG, ex.toString()); } return null;} |
13、android獲取存儲卡路徑以及使用情況:
/** 獲取存儲卡路徑 /
File sdcardDir=Environment.getExternalStorageDirectory();
/* StatFs 看文件系統(tǒng)空間使用情況 /
StatFs statFs=new StatFs(sdcardDir.getPath());
/* Block 的 size*/
Long blockSize=statFs.getBlockSize();
/** 總 Block 數(shù)量 /
Long totalBlocks=statFs.getBlockCount();
/* 已使用的 Block 數(shù)量 */
Long availableBlocks=statFs.getAvailableBlocks();
14 android中添加新的聯(lián)系人:
1 2 3 4 5 6 7 8 91011121314 | private Uri insertContact(Context context, String name, String phone) { ContentValues values = new ContentValues(); values.put(People.NAME, name); Uri uri = getContentResolver().insert(People.CONTENT_URI, values); Uri numberUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY); values.clear(); values.put(Contacts.Phones.TYPE, People.Phones.TYPE_MOBILE); values.put(People.NUMBER, phone); getContentResolver().insert(numberUri, values); return uri;} |
15、查看電池使用情況:
12 | Intent intentBatteryUsage = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY); startActivity(intentBatteryUsage); |
16、從res/raw打開文件
1 2 3 4 5 6 7 8 9101112131415161718192021 | public static String openFileFromRaw(Context context) throws IOException { String content = ""; InputStream inputStream = context.getResources().openRawResource(R.raw.provinces); if (inputStream != null) { BufferedReader buffreader = new BufferedReader(new InputStreamReader(inputStream)); String line; //分行讀取 try { while ((line = buffreader.readLine()) != null) { content += line + "n"; } } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } inputStream.close(); } return content ; } |
17 得到屏幕尺寸
123 | Display display = getWindowManager().getDefaultDisplay();int width = display.getWidth(); //寬int height = display.getHeight(); //高 |
18 關(guān)閉軟鍵盤
12345 | private void hideSoftInput() { InputMethodManager imm = (InputMethodManager) this .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } |
19 回退按鈕
1 2 3 4 5 6 7 8 91011121314151617181920212223 | public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { new AlertDialog.Builder(activity_login.this) .setTitle("退出系統(tǒng)") .setMessage("確定要退出系統(tǒng)嗎") .setPositiveButton("退出", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) // Leave .setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }).show(); } return false; } |
20 btn_selector
123456789 | <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- pressed --> <item android:state_pressed="true" android:drawable="@drawable/btn_press"/> <!-- focused --> <item android:state_focused="true" android:drawable="@drawable/btn"/> <!-- default --> <item android:drawable="@drawable/btn"/></selector> |
21 關(guān)閉游標(biāo)和數(shù)據(jù)庫
1 2 3 4 5 6 7 8 91011121314151617181920 | private void close(Cursor cursor, SQLiteDatabase database){ try { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } catch (Exception e) {} try { dbHelper.closeDb(database); } catch (Exception e) { } } |
22 MD5加密
1 2 3 4 5 6 7 8 910111213141516 | public static String md5(String string) { byte[] hash; try { hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Huh, MD5 should be supported?", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Huh, UTF-8 should be supported?", e); } StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { if ((b & 0xFF) < 0x10) hex.append("0"); hex.append(Integer.toHexString(b & 0xFF)); } return hex.toString().toLowerCase(); } |
23、系統(tǒng)的版本信息
1 2 3 4 5 6 7 8 91011121314151617181920 | public String[] getVersion(){ String[] version={"null","null","null","null"}; String str1 = "/proc/version"; String str2; String[] arrayOfString; try { FileReader localFileReader = new FileReader(str1); BufferedReader localBufferedReader = new BufferedReader( localFileReader, 8192); str2 = localBufferedReader.readLine(); arrayOfString = str2.split("\s+"); version[0]=arrayOfString[2];//KernelVersion localBufferedReader.close(); } catch (IOException e) { } version[1] = Build.VERSION.RELEASE;// firmware version version[2]=Build.MODEL;//model version[3]=Build.DISPLAY;//system version return version; } |
24、mac地址和開機(jī)時(shí)間
1 2 3 4 5 6 7 8 910111213141516171819202122 | public String[] getOtherInfo(){ String[] other={"null","null"}; WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if(wifiInfo.getMacAddress()!=null){ other[0]=wifiInfo.getMacAddress(); } else { other[0] = "Fail"; } other[1] = getTimes(); return other; } private String getTimes() { long ut = SystemClock.elapsedRealtime() / 1000; if (ut == 0) { ut = 1; } int m = (int) ((ut / 60) % 60); int h = (int) ((ut / 3600)); return h + " " + mContext.getString(R.string.info_times_hour) + m + " " + mContext.getString(R.string.info_times_minute); } |
25、CPU頻率,CPU信息:/proc/cpuinfo和/proc/stat
通過讀取文件/proc/cpuinfo系統(tǒng)CPU的類型等多種信息。
讀取/proc/stat 所有CPU活動(dòng)的信息來計(jì)算CPU使用率
下面我們就來講講如何通過代碼來獲取CPU頻率:
1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 | package com.orange.cpu;import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.io.InputStream;public class CpuManager { ** // 獲取CPU最大頻率(單位KHZ) // "/system/bin/cat" 命令行 // "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" 存儲最大頻率的文件的路徑** public static String getMaxCpuFreq() { String result = ""; ProcessBuilder cmd; try { String[] args = { "/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" }; cmd = new ProcessBuilder(args); Process process = cmd.start(); InputStream in = process.getInputStream(); byte[] re = new byte[24]; while (in.read(re) != -1) { result = result + new String(re); } in.close(); } catch (IOException ex) { ex.printStackTrace(); result = "N/A"; } return result.trim(); } **// 獲取CPU最小頻率(單位KHZ)** public static String getMinCpuFreq() { String result = ""; ProcessBuilder cmd; try { String[] args = { "/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq" }; cmd = new ProcessBuilder(args); Process process = cmd.start(); InputStream in = process.getInputStream(); byte[] re = new byte[24]; while (in.read(re) != -1) { result = result + new String(re); } in.close(); } catch (IOException ex) { ex.printStackTrace(); result = "N/A"; } return result.trim(); } **// 實(shí)時(shí)獲取CPU當(dāng)前頻率(單位KHZ)** public static String getCurCpuFreq() { String result = "N/A"; try { FileReader fr = new FileReader( "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"); BufferedReader br = new BufferedReader(fr); String text = br.readLine(); result = text.trim(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } ** // 獲取CPU名字** public static String getCpuName() { try { FileReader fr = new FileReader("/proc/cpuinfo"); BufferedReader br = new BufferedReader(fr); String text = br.readLine(); String[] array = text.split(":\s+", 2); for (int i = 0; i < array.length; i++) { } return array[1]; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }} |
26、內(nèi)存:/proc/meminfo
1 2 3 4 5 6 7 8 9101112 | public void getTotalMemory() { String str1 = "/proc/meminfo"; String str2=""; try { FileReader fr = new FileReader(str1); BufferedReader localBufferedReader = new BufferedReader(fr, 8192); while ((str2 = localBufferedReader.readLine()) != null) { Log.i(TAG, "---" + str2); } } catch (IOException e) { } } |