萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 進程優先級詳解:五大等級與 Service 前台提升機制

五大進程優先級(由高到低)

  1. 前台進程:正在與用戶互動的 Activity、執行中的 Service(onCreate/onStart/onDestroy)、BroadcastReceiver (onReceive)。系統極力保護不被回收。
  2. 可見進程:可見但非前台的 Activity(如被半透明 Activity 遮蓋)、綁定於可見 Activity 的 Service。極端記憶體不足才會回收。
  3. 服務進程:已啟動的 Service(startService),無可見 UI。優先級較低,但資源充足時不會被殺。
  4. 背景進程:無可見 Activity 且無啟動 Service 的進程。系統依 LRU 原則回收以釋放記憶體給前台進程。
  5. 空進程:已結束生命週期但被系統保留作快取,優先被回收。

Service 提升為前台進程

長時間運行任務(音樂播放、下載、定位)建議放在 Service 並呼叫 startForeground(),獲得最高優先級,幾乎不會被系統殺掉。

核心 API

  • startForeground(int id, Notification notification):設為前台,需提供持續性通知(Ongoing)。
  • stopForeground(boolean removeNotification):取消前台狀態。

實作步驟

// Service onStartCommand 中
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Notification noti = new NotificationCompat.Builder(this, CHANNEL_ID)
    .setContentTitle("播放中")
    .setContentText("音樂服務運行中")
    .setSmallIcon(R.drawable.ic_music)
    .setContentIntent(pi)
    .setOngoing(true)
    .build();

startForeground(97789, noti); // 唯一 ID

UI 執行緒與 ANR

  • 主執行緒(UI Thread)負責所有 UI 操作,耗時操作(網路、DB、複雜運算)必須移至子執行緒。
  • ANR 觸發條件:主執行緒 5 秒無回應、BroadcastReceiver onReceive 10 秒未完成。
  • 解決方案:Handler、AsyncTask(已棄用)、ExecutorService、Coroutines、RxJava 等非同步機制。

總結

理解進程優先級有助於設計穩健的後台服務;善用前台 Service 配合通知,可確保關鍵任務持續運行;嚴守主執行緒非阻塞原則,避免 ANR。

copyright © 萬盛學電腦網 all rights reserved