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

Android 系統工具類 SystemUtils 整理:常用系統操作一把抓

編輯:關於 Android 程式設計

近期需求大量涉及系統層面的操作,我在自己摸索加上四處搜集之後,整理出一支 SystemUtils 工具類,把這些零散的 API 集中管理,之後要用的時候不必每次重新查。

目前涵蓋的功能

  • 取得系統中所有已安裝 App、只取得使用者安裝的 App
  • 依套件名與啟動 Activity 查詢單一應用資訊
  • 跳轉 Wi-Fi 設定、切換 Wi-Fi 開關
  • 切換行動數據、切換 GPS
  • 調整系統音量、設定與讀取螢幕亮度
  • 跳轉系統設定頁
  • 遞迴取得資料夾底下所有檔案
  • 產生影片縮圖、以外部程式開啟影片檔

這支工具類我會持續補充,也歡迎一起交流。

列舉應用:PackageManager 是主角

取得所有可啟動的應用,靠的是 Intent 比對:

public static ArrayList getAllApp(Context context) {
    PackageManager manager = context.getPackageManager();
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    List<ResolveInfo> apps = manager.queryIntentActivities(mainIntent, 0);
    // 依名稱排序,讓列表有穩定順序
    Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));
    ArrayList appList = new ArrayList();
    for (ResolveInfo info : apps) {
        AppInfo appInfo = new AppInfo();
        appInfo.setAppLable(info.loadLabel(manager) + "");
        appInfo.setAppIcon(info.loadIcon(manager));
        appInfo.setAppPackage(info.activityInfo.packageName);
        appInfo.setAppClass(info.activityInfo.name);
        appList.add(appInfo);
    }
    return appList;
}

只想排除預先安裝的系統應用,判斷 ApplicationInfo 的 FLAG_SYSTEM 旗標即可:

ApplicationInfo ainfo = info.activityInfo.applicationInfo;
if ((ainfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
    // 只收使用者安裝的應用
}

網路與 GPS 開關

Wi-Fi 開關很單純:

WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wm.setWifiEnabled(enabled);

行動數據就沒這麼客氣了。系統沒有開放公開 API,只能繞道反射:取得 ConnectivityManager → 取出私有欄位 mService → 拿到 IConnectivityManager 實例 → 呼叫它隱藏的 setMobileDataEnabled(boolean)。這條路徑在不同 Android 版本上並不保證有效,且屬於非官方介面,正式上線前務必實機驗證。

GPS 切換則是發送一個帶特殊 data 的廣播意圖給系統設定:

Intent gpsIntent = new Intent();
gpsIntent.setClassName("com.android.settings",
        "com.android.settings.widget.SettingsAppWidgetProvider");
gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
gpsIntent.setData(Uri.parse("custom:3"));
PendingIntent.getBroadcast(context, 0, gpsIntent, 0).send();

音量與亮度

音量調整用 AudioManager,ADJUST_RAISE 等同按音量鍵:

AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
am.adjustStreamVolume(AudioManager.STREAM_SYSTEM,
        AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);

亮度則是寫入 Settings.System,並記得呼叫 notifyChange 通知系統:

ContentResolver resolver = activity.getContentResolver();
Uri uri = android.provider.Settings.System.getUriFor("screen_brightness");
int now = getScreenBrightness(activity);
now = now <= 225 ? now + 30 : 30;   // 每 30 遞增,撞到上限就回到 30
android.provider.Settings.System.putInt(resolver, "screen_brightness", now);
resolver.notifyChange(uri, null);

遞迴列舉檔案與影片縮圖

public static ArrayList<File> getFilesArray(String path) {
    File file = new File(path);
    File[] files = file.listFiles();
    ArrayList<File> listFile = new ArrayList<File>();
    if (files != null) {
        for (File f : files) {
            if (f.isFile()) {
                listFile.add(f);
            } else if (f.isDirectory()) {
                listFile.addAll(getFilesArray(f.toString()));
            }
        }
    }
    return listFile;
}

影片縮圖透過 ThumbnailUtils 兩步完成,先取原始縮圖再裁成指定尺寸。這裡有個省記憶體的眉角:若你要的寬高都小於 96×96,kind 就傳 MICRO_KIND,別用 MINI_KIND(512×384)硬解。

Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
        ThumbnailUtils.OPTIONS_RECYCLE_INPUT);

額外補充:開機清除指定應用的使用者資料

這個需求要註冊開機廣播,在 Intent.ACTION_BOOT_COMPLETED 時掃描已安裝套件,對指定名單呼叫 ActivityManager 的 clearApplicationUserData。問題是這個方法被系統隱藏了,因此同樣得靠反射取得:

Method targetMethod = null;
Method[] methods = am.getClass().getMethods();
for (Method m : methods) {
    if ("clearApplicationUserData".equals(m.getName())) {
        targetMethod = m;
        break;
    }
}
targetMethod.invoke(am, pkg, mClearDataObserver);

這裡有兩個前提條件必須滿足,少一個都跑不起來:

其一,android:sharedUserId="android.uid.system",讓應用以系統 uid 運行;其二,在 Android.mk 中加入 LOCAL_CERTIFICATE := platform,用平台簽章打包。同時別忘了在 Manifest 註冊 RECEIVE_BOOT_COMPLETED 與 CLEAR_APP_USER_DATA 權限。存檔若報錯,clean 一下專案即可。

使用提醒

這支工具類裡有幾個方法(行動數據切換、清除使用者資料、GPS 廣播)都走的是隱藏 API 或平台簽章路徑,只適用在系統應用或特定定制機型上,一般上架應用請勿直接沿用。其餘如列舉應用、亮度音量、縮圖產生等則是標準 API,可放心使用。

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