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

Android Service 元件完全解析:生命週期、啟動方式與前台服務

編輯:關於 Android 程式設計

Service 是 Android 四大元件之一。它沒有 UI 介面,可以在後台執行長時間的操作。其他元件可以 start 一個 Service,啟動之後它會在後台持續運行,無管用戶是否切換到了別的應用程式。此外,其他元件還可以 bind 到 Service 上與之互動,甚至進行跨行程操作(IPC)。典型用途包括:在後台處理網路請求、播放音樂、執行檔案 IO,或與 Content Provider 互動。

兩種型態

Started(已啟動)
當其他元件呼叫 startService() 啟動的 Service 就是 started。一旦啟動,它會在後台無限運行下去,即使啟動它的元件已經被銷毀。這種 Service 通常只做單一操作,而且不回傳結果給呼叫者,例如透過網路下載或上傳檔案。工作結束時,Service 必須手動把自己停掉。

Bound(已綁定)
當其他元件呼叫 bindService() 綁定時,Service 就是 bound。它提供客戶端/服務端介面,允許元件與 Service 互動、送出請求、取得結果,甚至跨行程操作。Bound Service 只在其他元件綁定於它時存活;多個元件可以同時綁定同一個 Service,但當所有元件都解綁後,Service 就被銷毀。

雖然這裡分開討論,但一個 Service 可以同時支援兩種型態——取決於你是否實作了 onStartCommand()(允許被 start)與 onBind()(允許被綁定)。

重要提醒:Service 運行在宿主行程的主執行緒上,它不會自己建立執行緒,也不會跑在獨立行程中(除非你明確指定)。因此若 Service 要做耗 CPU 或阻塞的操作(播放 MP3、網路請求等),你必須在內部自行建立新執行緒,否則 ANR 風險很高,主執行緒也無法專注在 UI 操作上。

核心回呼方法

建立 Service 時必須繼承 Service 或其子類,並覆寫以下關鍵回呼:

  • onStartCommand():當其他元件呼叫 startService() 時觸發。此方法執行後 Service 即在後台無限運行,你有責任在工作結束後呼叫 stopSelf() 或 stopService() 將它銷毀。若只提供綁定功能,則不需實作。
  • onBind():當其他元件呼叫 bindService() 時觸發。必須回傳一個 IBinder 作為與 Service 互動的介面;若不允許綁定,回傳 null。
  • :Service 首次建立時呼叫,只執行一次(在 onStartCommand() 或 onBind() 之前)。若 Service 已在運行則不會觸發。
  • onDestroy():Service 不再被使用或被銷毀時呼叫。要在這裡清理執行緒、監聽器、廣播接收器等資源。這是 Service 收到的最後一個回呼。

系統何時會殺掉 Service

Android 只在記憶體不足時才會強制終止 Service,因為系統必須優先保住持有用戶焦點的 Activity 所需的資源。優先順序大致如下:

  • 綁定到持有用戶焦點的 Activity 的 Service,很可能不會被殺。
  • 被宣告為前台運行的 Service,一般不會被殺。
  • 其他情況下,若 Service 是 started 且長時間運行,系統會隨時間把它移到後台任務清單的越後面位置,也就越容易被回收。

如果 Service 是被 started 的,你必須讓它能優雅地面對系統重啟:一旦資源恢復,系統會依 onStartCommand() 的回傳值決定是否重啟它。

在 Manifest 中宣告

與 Activity 一樣,所有 Service 都必須在 manifest 中宣告:

<manifest ...>
    ...
    <service android:name=".ExampleService">
        ...
    </service>
</manifest>

android:name 是唯一必填屬性,指定 Service 的類別名稱。應用發布後不應再修改這個名字,否則用明確 Intent 來 start 或 bind 的程式碼會有 crash 風險。

為了安全性,start 或 bind Service 時一律使用明確 Intent,且不要為 Service 宣告 intent-filter。若確實需要間接啟動,可以設定 filter 並排除特定元件名稱,但務必用 setPackage() 為 Intent 指定套件,確定性才足夠。

另一個作法是加入 android:exported="false",確保 Service 只對自己的應用可用——即使其他應用使用明確 Intent 也無法啟動它。

建立 Started Service:IntentService

大多數 started Service 不需要處理並發請求,因此繼承 IntentService 通常是最省事的做法。它會幫你處理:

  1. 建立一個預設工作執行緒,用來執行傳入 onStartCommand() 的 Intent,且與主執行緒獨立。
  2. 建立工作佇列,每次只把一個 Intent 送進 onHandleIntent(),不必擔心多執行緒問題。
  3. 所有請求處理完畢後自動停止,不需呼叫 stopSelf()。
  4. 提供 onBind() 的預設實作,回傳 null。
  5. 提供 onStartCommand() 的預設實作,把 Intent 送進工作佇列後交給 onHandleIntent()。
public class HelloIntentService extends IntentService {

    /** 建構子必須呼叫 super IntentService(String),參數為工作執行緒的名稱 */
    public HelloIntentService() {
        super("HelloIntentService");
    }

    /**
     * IntentService 會在預設工作執行緒上呼叫此方法,
     * 方法回傳後,IntentService 會視情況停止服務。
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        // 這裡通常會做下載檔案之類的工作,範例中單純睡 5 秒
        long endTime = System.currentTimeMillis() + 5 * 1000;
        while (System.currentTimeMillis() < endTime) {
            synchronized (this) {
                try {
                    wait(endTime - System.currentTimeMillis());
                } catch (Exception e) { }
            }
        }
    }
}

就這樣:一個建構子加上 onHandleIntent()。若你要覆寫 onCreate()、onStartCommand() 或 onDestroy(),務必記得呼叫父類實作,否則 IntentService 無法正確管理它的工作執行緒。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    return super.onStartCommand(intent, flags, startId);
}

建立 Started Service:直接繼承 Service

若 Service 需要處理多執行緒(不是透過工作佇列),就該直接繼承 Service。以下範例實作了與上面 IntentService 版本相同的功能:

public class HelloService extends Service {
    private Looper mServiceLooper;
    private ServiceHandler mServiceHandler;

    // 接收執行緒訊息的 Handler
    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            // 這裡通常會做下載檔案之類的工作,範例中單純睡 5 秒
            long endTime = System.currentTimeMillis() + 5 * 1000;
            while (System.currentTimeMillis() < endTime) {
                synchronized (this) {
                    try {
                        wait(endTime - System.currentTimeMillis());
                    } catch (Exception e) { }
                }
            }
            // 用 startId 停止,避免在處理另一個任務途中把服務停掉
            stopSelf(msg.arg1);
        }
    }

    @Override
    public void onCreate() {
        // 建立獨立執行緒,避免阻塞主執行緒;
        // 同時設為背景優先級,讓 CPU 密集工作不干擾 UI
        HandlerThread thread = new HandlerThread("ServiceStartArguments",
                Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
        // 每個啟動請求都送一則訊息,並帶入 startId
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        mServiceHandler.sendMessage(msg);

        // 被系統回收後重新建立
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;   // 不提供綁定
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
    }
}

可以看到工作量比 IntentService 多不少。但因為請求是在 onStartCommand() 中處理的,你可以並發處理多個請求(為每個請求建立執行緒立即執行,而非排隊等待)。

onStartCommand() 的三種回傳值

  • START_NOT_STICKY:系統回收後不會重新建立 Service,除非有 pending intent。這是最安全的方式,可避免運行不必要的 Service,應用也能自行重啟未完成的任務。
  • START_STICKY:系統會重新建立 Service 並再次呼叫 onStartCommand(),但不會重送最後一個 Intent(改傳 null),除非有 pending intent。適合媒體播放器這類「不執行具體命令、只是持續運行等待新任務」的 Service。
  • START_REDELIVER_INTENT:系統會重新建立 Service、再次呼叫 onStartCommand(),並重送最後一個 Intent;pending intents 也會依序送達。適合下載檔案這種需要立刻被喚醒的情境。

啟動與停止 Service

在 Activity 或其他元件中,傳入指定 Service 的 Intent 即可啟動:

Intent intent = new Intent(this, HelloService.class);
startService(intent);

startService() 會立即回傳,系統隨後呼叫 onStartCommand();若 Service 尚未運行,會先呼叫 onCreate()。請注意不要直接呼叫 onStartCommand()。

若 Service 不提供綁定,Intent 就是唯一的對外溝通管道。反之,若 Service 需要回傳結果,啟動它的客戶端可以建立一個用於廣播的 PendingIntent(getBroadcast())傳進去,Service 就能透過廣播送出結果。

多次啟動請求會導致多次 onStartCommand() 呼叫,但只需要一次停止請求就能停掉 Service。

停止 Service:started Service 必須自行管理生命週期。系統不會主動停它(除非要回收資源),因此 Service 要呼叫 stopSelf(),或由其他元件呼叫 stopService()。

若 Service 在 onStartCommand() 中並發處理請求,處理完一個就停掉自己顯然是錯的——你可能已經收到了新請求。這時應使用 stopSelf(int),傳入對應的 startId。若在你呼叫 stopSelf(int) 前又來了一個啟動請求,ID 對不上,Service 就不會被停掉。

工作完成後主動停掉 Service,對節省系統資源與電量都很重要。另外,即使 Service 有啟用 binding,只要收到過 onStartCommand() 呼叫,仍需手動停止。

建立 Bound Service

Bound Service 讓應用元件呼叫 bindService() 建立長時間存在的連接(通常不搭配 startService())。當你想讓 Activity 與 Service 互動,或透過 IPC 把功能開放給其他應用時,就該用它。

實作上要定義 onBind() 並回傳 IBinder,它定義了通訊介面。客戶端呼叫 bindService() 取得介面後即可呼叫 Service 的方法。Service 只在其綁定的元件存在時存活,因此當沒有客戶端綁定時系統會自動銷毀它——不需要像 started Service 那樣手動停止。

多個客戶端可同時綁定同一個 Service;每個客戶端用完後呼叫 unbindService() 解綁,全部解綁後 Service 即被銷毀。由於實作方式較多、複雜度也高於 started Service,細節建議參考官方 Bound Services 專章。

給用戶發送通知

Service 運行期間可以透過 Toast 或狀態欄通知提醒用戶事件。一般來說,當後台任務完成時(例如檔案下載完畢),用狀態欄通知是最合適的做法:用戶在展開的視圖中點選通知後,可以直接開啟一個 Activity 做後續操作。

前台 Service

前台 Service 被視為用戶可感知的,因此不是低記憶體時的回收候選。它必須在狀態欄有一則屬於「進行中」的通知,且除非 Service 被停止或移出前台,通知不會消失。

典型例子是音樂播放器:用戶明確知道它在運作,狀態欄通知可以顯示目前播放的歌曲,並讓用戶點擊跳回播放器 Activity。

Notification notification = new Notification(
        R.drawable.icon, getText(R.string.ticker_text), System.currentTimeMillis());

Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(this,
        getText(R.string.notification_title),
        getText(R.string.notification_message),
        pendingIntent);

startForeground(ONGOING_NOTIFICATION_ID, notification);

注意:通知的 ID 不能為 0。

要移出前台,呼叫 stopForeground(),它接受一個 boolean 參數決定是否同時移除狀態欄通知。這個方法不會停止 Service;若你想在前台狀態下停止 Service,通知也會一併消失。

管理 Service 的生命週期

public class ExampleService extends Service {
    int mStartMode;         // 被回收後的行為
    IBinder mBinder;        // 供客戶端綁定的介面
    boolean mAllowRebind;   // 是否使用 onRebind

    @Override
    public void onCreate() {
        // Service 正在被建立
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Service 因 startService() 而啟動
        return mStartMode;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // 有客戶端以 bindService() 綁定
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // 所有客戶端都已 unbindService()
        return mAllowRebind;
    }

    @Override
    public void onRebind(Intent intent) {
        // onUnbind() 已呼叫過之後,又有客戶端綁定
    }

    @Override
    public void onDestroy() {
        // Service 不再被使用,即將銷毀
    }
}

與 Activity 不同,這些回呼並不要求呼叫父類實作。

實作這些方法後,你可以監控兩個循環:

(1)完整生命週期:從 onCreate() 到 onDestroy() 回傳。類似 Activity,Service 在 onCreate() 做初始化、在 onDestroy() 釋放資源。例如音樂播放器可以在 onCreate() 建立播放執行緒,在 onDestroy() 停掉它。不管 Service 是用 startService() 還是 bindService() 建立,這兩個回呼都會被呼叫。

(2)活動時間:從 onStartCommand() 或 onBind() 開始。這兩個方法分別接收 startService() 或 bindService() 傳入的 Intent。若 Service 是 started,活動時間會延續到生命週期結束;若是 bound,則在 onUnbind() 回傳時結束。

最後一個容易誤會的點:被 stopSelf() 或 stopService() 停掉的 started Service,並沒有對應的回呼(不存在 onStop())。因此除非 Service 仍綁定著某個客戶端,一旦停止系統就會直接銷毀它,onDestroy() 是唯一會收到的通知。

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