Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發常用經典程式碼片段精選

編輯:關於 Android 程式設計

日常開發中有些小功能,寫過一次之後往往還要再寫一次。本文把一批實用度極高的程式碼片段整理在一起,涵蓋圖片處理、系統服務、Intent 呼叫與裝置資訊取得等常見需求,方便隨時翻查。

1. 旋轉圖片

 Bitmap bitmapOrg = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.moon); Matrix matrix = new Matrix(); matrix.postRotate(-90);// 旋轉角度 Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, bitmapOrg.getWidth(), bitmapOrg.getHeight(), matrix, true); BitmapDrawable bmd = new BitmapDrawable(resizedBitmap); 

2. 取得手機號碼

 // 建立電話管理 TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE); // 取得手機號碼 String phoneId = tm.getLine1Number(); 

需在 manifest 中加入 <uses-permission android:name="android.permission.READ_PHONE_STATE" />。注意此段在模擬器上無法正常運作,且較新版本 Android 需要執行期授權。

3. 格式化 strings.xml 中的字串

 <!-- strings.xml --> <string name="my_text">Thanks for visiting %s. You age is %d!</string> // Java 端 String.format(getString(R.string.my_text), "oschina", 33); 

4. 設定全螢幕

方法 A,在 Java 程式碼中設定:

 /** 全螢幕設定,隱藏視窗所有裝飾 */ requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 

方法 B,在 AndroidManifest.xml 中透過 theme 指定:

 <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. 讓 Activity 以對話框形式呈現

 android:theme="@android:style/Theme.Dialog" 

6. 檢查網路連線狀態

 ConnectivityManager con = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE); boolean wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); boolean internet = con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting(); 

記得補上權限:

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

7. 判斷某個 Intent 是否可用

直接發 Intent 而裝置上沒有對應 App 會導致崩潰,先檢查再呼叫才是安全做法。

 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. 撥打電話

 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. 寄送 Email

 Intent i = new Intent(Intent.ACTION_SEND); //i.setType("text/plain"); // 模擬器請使用這行 i.setType("message/rfc822") ; // 真機上使用這行 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. 開啟瀏覽器

 Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("https://vaiyanzi.cnblogs.com")); startActivity(viewIntent); 

11. 取得裝置唯一識別碼

 String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID); 

12. 取得本機 IP 位址

 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. 取得外部儲存空間路徑與使用量

 /** 取得記憶卡路徑 */ File sdcardDir = Environment.getExternalStorageDirectory(); /** StatFs 檢視檔案系統空間使用情況 */ StatFs statFs = new StatFs(sdcardDir.getPath()); /** 每個 Block 的大小 */ Long blockSize = statFs.getBlockSize(); /** Block 總數 */ Long totalBlocks = statFs.getBlockCount(); /** 可用的 Block 數 */ Long availableBlocks = statFs.getAvailableBlocks(); 

14. 新增聯絡人

 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. 開啟電力使用情況

 Intent intentBatteryUsage = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY); startActivity(intentBatteryUsage); 

16. 取得執行中的行程資訊

 ActivityManager mActivityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> mRunningProcess = mActivityManager.getRunningAppProcesses(); int i = 1; for (ActivityManager.RunningAppProcessInfo amProcess : mRunningProcess) { Log.e("homer Application", (i++) + " PID = " + amProcess.pid + "; processName = " + amProcess.processName); } 

使用提醒

這些片段多數寫於 Android 早期版本,直接複製到新專案時要留意兩件事:一是權限模型已改為執行期動態授權,READ_PHONE_STATE、READ_CONTACTS 這類敏感權限都必須在執行時向使用者請求;二是部分 API 已被標記為不建議使用,例如 getRunningAppProcesses() 在後續版本回傳的資訊大幅受限,getLine1Number() 也需要權限與讀取限制。理解原理之後,再對照目前版本的官方文件調整,才能用得安心。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved