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

Service 被系統回收後的生命週期實驗:onDestroy 真的會被呼叫嗎?

編輯:關於 Android 程式設計

前陣子面試時反覆被問到同一個關於 Service 的問題,值得花點篇幅記錄。

背景是這樣的:先前做的一個 App 有個需求——開機後啟動一個 Service,在 Service 中另開執行緒比對使用者設定的時間,到點時發出提醒。描述這個做法時,面試官追問:如果這個 Service 被系統或其他應用程式回收了,你打算怎麼辦?

我當時的回答是在 onDestroy() 中處理善後。面試官指出,onDestroy() 並不會被呼叫。

這個回應確實點出了關鍵:Service 的 onDestroy() 並不是「保證執行」的回呼。正常流程下(例如呼叫 stopService 或 stopSelf)它會被觸發;但當程序遭到強制終止、系統為釋放記憶體而直接殺掉進程時,Linux 層面的 SIGKILL 無法攔截,Java 層的任何回呼自然都不會有執行的機會。

那麼實際情況究竟如何?還是用程式碼驗證最可靠。

步驟一:建立 Activity 並以按鈕啟動 Service

package com.zhenghuiy.killedservicelifecycletest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

    private Button startServiceBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    private void initViews() {
        startServiceBtn = (Button) findViewById(R.id.startService);
        startServiceBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.startService) {
            Intent intent = new Intent();
            intent.setClass(this, MyService.class);
            this.startService(intent);
        }
    }
}

步驟二:在 Service 中覆寫所有相關回呼並逐一記錄

package com.zhenghuiy.killedservicelifecycletest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service implements Runnable {

    /*
     * 以 bindService 形式呼叫時會走 onBind;
     * 以 startService 呼叫則走 onStartCommand。
     * 另外 onBind 是抽象方法,必須覆寫。
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        showLog("onStartCommand is called");
        // Service 運行於 UI 主執行緒,為避免阻塞而被關閉,另開一條執行緒
        new Thread(this).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        showLog("onBind is called");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        showLog("onCreate is called");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        showLog("onDestroy is called");
    }

    /* onStart 已過時,2.0 之後請使用 onStartCommand */
    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        showLog("onStart is called, the Intent action is " + intent.getAction());
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        showLog("onTaskRemoved is called, the Intent action is " + rootIntent.getAction());
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        showLog("onTrimMemory is called, the level is " + level);
    }

    private void showLog(String text) {
        Log.v(this.getClass().getName(), text);
    }

    @Override
    public void run() {
        while (true) { }
    }
}

這裡刻意讓 run() 跑一個無窮迴圈,是為了製造「Service 正在忙碌」的情境,方便觀察系統在不同壓力下的處理順序。

觀察到的現象與結論

實驗可以歸納出幾點:

1. 正常停止(stopService / stopSelf)時,onDestroy() 會被呼叫,這是唯一可靠的收尾時機。

2. 當程序被系統直接終止(例如低記憶體時的回收、在手機的最近任務清單中劃掉應用),出發點是程序層級的強制結束,onDestroy() 不一定被觸發。實測中劃除任務時會先走到 onTaskRemoved(),但這也不能視為必然。

3. onTrimMemory() 只能作為「系統正在吃緊」的預警訊號,並不代表 Service 即將被銷毀,適合用來釋放快取而非保存關鍵狀態。

因此,回到面試那個問題,正確的思路不是「在 onDestroy 中補救」,而是:

● 關鍵狀態要即時持久化(SharedPreferences、資料庫、檔案),不要等到生命週期結束才寫入;

● 若任務不容中斷,改用 START_STICKY 讓系統在資源允許時重建 Service,並在 onStartCommand 中依 intent 內容判斷是首次啟動還是重建;

● 需要更高存活機制的話,可考慮前台服務搭配通知,或改用 JobScheduler / WorkManager 這類由系統調度的方案;

● 開機自啟的情境,則應把 BroadcastReceiver 與 Service 的職責分開,並在 Service 中做好冪等設計,避免重複啟動造成多個執行緒同時運行。

結論一句話:不要把 Service 當成保證會善終的容器。它的生命週期在異常情況下會被直接截斷,唯有把狀態寫進持久化儲存,才是真正可靠的設計。

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