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

Android Service 的啟動、關閉與生命週期全解析

編輯:關於 Android 程式設計

Service 是 Android 四大元件之一,它可以在一段不定的時間內於後台運行,且不與使用者直接互動。

Service 的適用場景很多:例如播放多媒體時使用者切換到了其他 Activity,此時程式仍需在後台繼續播放;又或者需要持續監聽某個系統狀態的變化,比如偵測 SD 卡上的檔案變動。

生命週期

context.startService() 的啟動流程:

context.startService() → onCreate() → onStart() → Service running → context.stopService() → onDestroy() → Service stop

如果 Service 尚未運行,系統會先調用 onCreate(),再調用 onStart();如果 Service 已經在運行,則只調用 onStart()。因此同一個 Service 的 onStart 可能被重複調用多次。

stopService 時會直接走到 onDestroy。若調用者自己退出而沒有呼叫 stopService,Service 會一直在後台運行,直到下一次有元件啟動它時,才可以透過 stopService 將其關閉。

所以 startService 的生命週期為:onCreate → onStart(可多次)→ onDestroy。

context.bindService() 的啟動流程:

context.bindService() → onCreate() → onBind() → Service running → onUnbind() → onDestroy() → Service stop

onBind() 會回傳一個 IBind 介面實例給客戶端,讓客戶端得以回調 Service 的方法,例如取得 Service 實例、查詢運行狀態或執行其他操作。此時調用者(Context,例如 Activity)就與 Service 綁定在一起,當 Context 退出時,Service 會依序觸發 onUnbind 與 onDestroy 而結束。

所以 bindService 的生命週期為:onCreate → onBind(僅一次)→ onUnbind → onDestroy。

值得注意的是:在 Service 每一次的開啟關閉過程中,只有 onStart 可能被多次調用(透過多次 startService),而 onCreate、onBind、onUnbind、onDestroy 在同一個生命週期內都只會被調用一次。

開啟與關閉的方式

啟動有兩種:context.startService() 與 context.bindService()
關閉有兩種:context.stopService() 與 context.unbindService()

一個完整範例

先在清單檔中註冊:

Service 本體:

package com.yydcdut.servicestudy1;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class PhoneStatusService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        System.out.println("onCreate");
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        System.out.println("onStart");
        // 監聽電話狀態的變化
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        tm.listen(new MyPhoneStatusListener(), PhoneStateListener.LISTEN_CALL_STATE);
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        System.out.println("onDestroy");
        super.onDestroy();
    }
}

狀態監聽器:

class MyPhoneStatusListener extends PhoneStateListener {
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:   // 空閒
            break;
        case TelephonyManager.CALL_STATE_RINGING: // 響鈴
            System.out.println("發現來電!!!!!");
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK: // 通話狀態
            break;
        default:
            break;
        }
        super.onCallStateChanged(state, incomingNumber);
    }
}

界面上的兩個按鈕負責啟動與關閉:

public void click(View view) {
    Intent intent = new Intent(getApplicationContext(), PhoneStatusService.class);
    startService(intent);
}

public void click2(View view) {
    Intent intent = new Intent(getApplicationContext(), PhoneStatusService.class);
    stopService(intent);
}

把日誌打印出來跑一遍,就能清楚看到 onCreate、onStart、onStartCommand、onDestroy 的實際觸發順序,這比死記生命週期圖表有效得多。

補充一點實務上的注意事項:自 Android 8.0 起,後台啟動 Service 已受到嚴格限制,需要改用 startForegroundService 並搭配通知列,或改用 WorkManager 這類方案。上面的範例適用於早期版本的理解與學習。

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