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

取得手機背景執行服務清單:ActivityManager 與 RunningServiceInfo

編輯:關於 Android 程式設計

想列出裝置上目前正在背景執行的服務,靠的是 ActivityManager 提供的 getRunningServices()。它回傳 RunningServiceInfo 清單,每筆資料都帶有 process、pid、client 數量、崩潰次數等資訊,做診斷工具時很實用。

public static String getRunningServicesInfo(Context context) {
    StringBuffer serviceInfo = new StringBuffer();

    final ActivityManager activityManager =
            (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

    // 最多取 100 筆
    List<RunningServiceInfo> services = activityManager.getRunningServices(100);
    Iterator<RunningServiceInfo> l = services.iterator();

    while (l.hasNext()) {
        RunningServiceInfo si = l.next();
        serviceInfo.append("\npid: ").append(si.pid);
        serviceInfo.append("\n\nname: ").append(si.service);
        serviceInfo.append("\n\nprocess: ").append(si.process);
        serviceInfo.append("\n\ncrashCount: ").append(si.crashCount);
        serviceInfo.append("\n\nclientCount: ").append(si.clientCount);
        serviceInfo.append("\n============================");
        serviceInfo.append("\n\n\n");
    }
    return serviceInfo.toString();
}

各欄位的意義

  • service:服務元件的完整類別名稱,通常是最有用的一項
  • process:服務所在的行程名稱
  • pid:行程 ID
  • clientCount:目前有多少個客戶端繫結到這個服務
  • crashCount:這個服務曾經崩潰的次數
  • activeSince / lastActivityTime:啟動時間與最後活動時間,是時間戳,需自行格式化

重要提醒

這個方法從 Android 5.0(API 21)起已被標記為 @Deprecated,官方說明是僅回傳呼叫者自己的服務,無法再看到其他 App 的服務——這其實是隱私權限收緊的結果,早期版本那種「能看到全機服務」的行為在現代 Android 上已不可行。

因此若你的目的是:

  • 檢視自己的服務狀態:改用 ServiceCompat 或自行維護一份服務註冊表,並搭配 startForeground() 的回報機制。
  • 做效能/流量監控:Android 已提供 UsageStatsManager(需 PACKAGE_USAGE_STATS 特殊權限)與 NetworkStatsManager,是官方推薦的替代方案。
  • 單純除錯:直接看 adb shell dumpsys activity services 的輸出,資訊比這個 API 完整得多。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved