Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Service 如何避免被系統輕易結束:onStartCommand 回傳值與常駐策略

編輯:Android 開發實例

Service 是 Android 的一種元件,層級與 Activity 相當,但它沒有自己的介面,只能以後台方式運行,並可與其他元件互動。

開發過程中,每次呼叫 startService(Intent),系統都會回呼該 Service 的 onStartCommand(Intent, int, int),我們通常在此處理實際工作。這個方法的回傳值決定了服務被系統結束後的行為,是寫常駐服務時最需要先弄懂的一塊。

一、onStartCommand 的四種回傳值

START_STICKY:若服務行程被 kill 掉,系統會保留服務「已啟動」的狀態,但不保留原本送交的 Intent 物件。隨後系統會嘗試重新建立服務,由於狀態仍是啟動中,重建後一定會呼叫 onStartCommand()。若這段期間沒有新的啟動命令送達,傳入的 Intent 參數會是 null——這點在寫程式時必須防呆,否則容易 NullPointerException。

START_NOT_STICKY:非黏性的。執行完 onStartCommand() 後若服務被異常 kill,系統不會自動重啟它。

START_REDELIVER_INTENT:重傳 Intent。執行完 onStartCommand() 後若服務被異常 kill,系統會自動重啟並把最後一個未處理的 Intent 再送進來,適合用「任務不可中斷」的場景(例如一筆必須完成的上傳)。

START_STICKY_COMPATIBILITY:START_STICKY 的相容版本,但不保證服務被 kill 後一定能重啟。

二、讓服務盡量存活的做法

1. 回傳 START_STICKY 系列

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
   return START_STICKY_COMPATIBILITY;
   // return super.onStartCommand(intent, flags, startId);
 }

或者帶入 flags 後交給父類處理:

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
   flags = START_STICKY;
   return super.onStartCommand(intent, flags, startId);
   // return START_REDELIVER_INTENT;
 }

 @Override
 public void onStart(Intent intent, int startId) {
   // 再次動態註冊廣播
   IntentFilter localIntentFilter = new IntentFilter("android.intent.action.USER_PRESENT");
   localIntentFilter.setPriority(Integer.MAX_VALUE);
   myReceiver searchReceiver = new myReceiver();
   registerReceiver(searchReceiver, localIntentFilter);
   super.onStart(intent, startId);
 }

2. 在 onDestroy() 中重啟自己

 public void onDestroy() {
   Intent localIntent = new Intent();
   localIntent.setClass(this, MyService.class);
   // 銷毀時重新啟動Service
   this.startService(localIntent);
 }

3. 建立高優先級廣播接收器

 public class myReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
     context.startService(new Intent(context, MyService.class));
   }
 }

4. 在 AndroidManifest.xml 中註冊

 <receiver android:name=".myReceiver" >
   <intent-filter android:priority="2147483647" ><!--優先級最高-->
     <!-- 系統啟動完成後會調用 -->
     <action android:name="android.intent.action.BOOT_COMPLETED" />
     <!-- 解鎖完成後會調用 -->
     <action android:name="android.intent.action.USER_PRESENT" />
     <!-- 監聽情景切換 -->
     <action android:name="android.media.RINGER_MODE_CHANGED" />
   </intent-filter>
 </receiver>

 <service android:name=".MyService" >

註:解鎖、開機完成、場景切換這類監聽需要對應權限,例如:

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

三、不同 kill 情境的應對

1. 設定中 stop service——在 onDestroy() 中呼叫 startService() 重啟。

2. 設定中 force stop——攔截系統的 android.intent.action.PACKAGE_RESTARTED 廣播。需要注意的是,正常使用者在應用資訊頁按下「強制停止」後,系統會將該應用標記為「已停止」,此後它接收不到任何 BOOT_COMPLETED 廣播,也不會被自動拉起,這是系統刻意設計的保護。

3. 被第三方清理軟體 kill 掉 running task——可嘗試提升服務優先級、變更簽名,或把應用放到 system/app 下。

相較於 /data/app 下的應用,放在 /system/app 下的應用享有更多特權。例如在 Manifest 中把 persistent 設為 true,就能讓它免受 low memory killer 影響,如系統應用 Phone 的宣告:

 <application
   android:name="PhoneApp"
   android:persistent="true"
   android:label="@string/dialerIconLabel"
   android:icon="@drawable/ic_launcher_phone">
   ...
 </application>

設定後該應用相當於被提升到系統核心層級。

四、給今天的開發者的提醒

上面這些技巧寫於 Android 4.x 時代,當時第三方清理軟體橫行,「保活」是一門顯學。但必須清楚說明:從 Android 8.0(Oreo)開始,系統對背景應用的限制大幅收緊,startService() 在應用退到背景後會直接拋 IllegalStateException;Android 9 進一步限制 BOOT_COMPLETED 等隱含廣播;後續版本又加入了待處理 Intent 佇列、Doze 模式與 App Standby 桶等機制。android:persistent="true" 也只對系統簽名的應用有效,一般應用放上 /system/app 需要 root 或自製 ROM。

換句話說,如今「讓服務永不被殺」既做不到,也不該追求。正確方向是依需求選擇合適的工具:非即時的延遲任務用 WorkManager;需要使用者能感知的長任務(音樂播放、導航、檔案傳輸)用前台服務並顯示通知;即時通訊類則可使用 Firebase Cloud Messaging 由系統代為喚醒。理解 START_STICKY 這類回傳值的語意仍然重要,但請把它當成「服務被回收後如何正確恢復」的設計依據,而不是對抗系統機制。希望本文對大家的 Android 開發有所幫助。

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