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

Android 常用工具方法整理

編輯:關於 Android 程式設計

時間與裝置資訊

開發中常需要格式化時間、取得裝置識別碼與系統版本。

public static String getDataTime(String format) {
    SimpleDateFormat df = new SimpleDateFormat(format);
    return df.format(new Date());
}
public static String getPhoneIMEI(Context context) {
    TelephonyManager tm = (TelephonyManager)
        context.getSystemService(Context.TELEPHONY_SERVICE);
    return tm.getDeviceId();
}

網路狀態判斷

public static boolean checkNet(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
        context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    return info != null;
}

模擬 Home 鍵

public static void goHome(Context context) {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

這些方法可整理成工具類,減少重複程式碼。但涉及隱私或系統權限時,仍需注意平台規範與使用者授權。

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