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

Android Service 完整整理:生命週期、通訊方式與 IntentService

編輯:關於 Android 程式設計

Service 是什麼

Service 是 Android 四大元件之一。當你有些「耗時但不需要跟使用者互動」的工作要做時,就該考慮它。常見場景包括:後台上傳與下載、防毒或監控類應用需要常駐並由 Intent 驅動、聊天與社群應用需要定時送心跳維持線上狀態等。

有兩個常見誤解要先打掉:

  • 它不是獨立進程。預設情況下 Service 與 App 跑在同一個進程裡,除非你明確定義成遠程 Service。
  • 它不是子線程。Service 的 callback 跑在主線程,所以它一樣不能做耗時操作,該開的執行緒還是要開。

它有兩種啟動方式,也是它的兩個主要特性:

  1. Context.startService():告訴系統有後台任務需要執行,請系統安排。
  2. Context.bindService():對外暴露功能,建立一條較長的連線,讓 Service 能與多個 client 溝通互動。

Service 的生命週期

兩種啟動方式下的生命週期對比如下:

Service 兩種啟動方式的生命週期對比圖

startService() 啟動:訪問者與 Service 之間沒有關聯,即使發起者離開了,Service 依然運行,必須由 Context.stopService() 結束,結束時會回呼 onDestroy()。適合彼此沒有互動需求的情況。

Service 建立時呼叫 onCreate();建立之後重複呼叫 startService() 不會再次觸發 onCreate(),Service 不會被重複建立,但每次你都會走一次 onStartCommand()(接著是已棄用的 onStart())。

bindService() 啟動:訪問者與 Service 綁在一起,訪問者一旦退出,Service 隨之終止。適合需要呼叫 Service 方法或傳遞參數的情況。

Service 尚未建立時,系統先呼叫 onCreate(),接著是 onBind(),此時兩者完成綁定。若訪問者要與 Service 通訊,onBind() 必須回傳一個 Ibinder 物件。訪問者離開時,系統先呼叫 onUnbind(),再呼叫 onDestroy()。若 Service 已被綁定,重複呼叫 bindService() 不會造成重複建立與綁定。

解除綁定用 unbindService(),它同樣會觸發 onUnbind() → onDestroy()。要注意的是重複呼叫 unbindService() 會丟出 java.lang.IllegalArgumentException: Service not registered。

因此,若只在 Activity 可見期間需要與 Service 互動,應該在 onStart() 綁定、onStop() 解除綁定;若希望 Activity 即使停止也能收到回應,可以在 onCreate() 綁定、onDestroy() 解除綁定。但這代表 Activity 整個生命週期都佔著這條連線,如果 Service 在另一個進程,反而增加了該進程的負擔,讓它更容易被系統回收。

兩種方式混用時的行為

對同一個 Service 同時使用 startService() 與 bindService(),onCreate() 依然只會執行一次。這種情況下,必須等到 unBindService() 之後,Service 才能被真正銷毀。

client: startService() -> bindService() -> stopService() / unBindService() -> unBindService() / stopService()
service: onCreate() -> onStartCommand() -> onStart() -> onBind() -> onServiceConnected() -> onUnBind() -> onDestroy()

client: bindService() -> startService() -> stopService() / unBindService() -> unBindService() / stopService()
service: onCreate() -> onBind() -> onServiceConnected() -> onStartCommand() -> onUnBind() -> onDestroy()

幾個容易踩到的細節:

  1. 先 bindService 再 startService:綁定的 Activity 退出時,Service 只會執行 unBind 而不會 onDestroy,因為曾經被 startService 過,會留下一個與調用者無關聯的 Service 繼續存在。
  2. 先 bindService 再 startService,然後呼叫 stopService:onDestroy 不會立刻執行,因為還有 Activity 綁著它。要立刻銷毀,得先解除綁定。

另外,onStartCommand(Intent intent, int flags, int startId) 的參數與回傳值值得留意:flags 預設為 0(對應 START_STICKY_COMPATIBILITY);startId 是唯一整數,多次呼叫時呈 0、1、2… 遞增。回傳值則有三種選擇:

  • START_NOT_STICKY:Service 因記憶體不足被 kill 後,即使日後記憶體充足也不會重建,除非 client 明確再次 startService。
  • START_STICKY:被 kill 後,系統在記憶體足夠時會嘗試重建並回呼 onStartCommand(),但此時 Intent 為 null(PendingIntent 除外)。
  • START_REDELIVER_INTENT:與上者差異在於回呼時 Intent 非空,會是最後一次 startService 傳入的 Intent。

與 Service 溝通的幾種方式

1. Binder 綁定

建立 Service 類別,並設計一個內部 Binder 子類別,把要對外開放的 public 方法定義在裡面。

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class DemoService extends Service {
    private static final String TAG = "DemoService";
    private static final int NOTIFICATION = 101;
    private NotificationManager mNM;
    private final DemoBinder demoBinder = new DemoBinder();

    public class DemoBinder extends Binder {
        public DemoService getService() {
            return DemoService.this;
        }

        public void upload() {
            Log.d(TAG, "upload: ");
        }
    }

    // 允許綁定時回傳 IBinder,不允許則回傳 null
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
        return demoBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        showNotification();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind: ");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
        mNM.cancel(NOTIFICATION);
    }

    private void showNotification() {
        PendingIntent contentIntent = PendingIntent.getActivity(
                this, 0, new Intent(this, MainActivity.class), 0);
        Notification notification = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setTicker("Service 已啟動")
                .setWhen(System.currentTimeMillis())
                .setContentTitle("DemoService 正在運行")
                .setContentText("測試 Service")
                .setContentIntent(contentIntent)
                .getNotification();
        mNM.notify(NOTIFICATION, notification);
    }
}

別忘了在 AndroidManifest.xml 註冊:

<service
    android:name=".DemoService"
    android:enabled="true"
    android:exported="true" />

Service 元素的常見屬性:

  • android:name:服務類別名稱。
  • android:label:服務顯示名稱,不設定則預設用類別名稱。
  • android:icon:服務圖示。
  • android:permission:宣告此服務的權限,只有具備該權限的應用才能控制或連線。
  • android:process:是否運行在另一個進程,設定後會在包名後附加該字串作為進程名。
  • android:enabled:設為 true 時服務會被系統啟動,不設定預設為 false。
  • android:exported:是否允許其他應用控制或連線,不設定預設為 false。

client 端透過 bindService(Intent service, ServiceConnection conn, int flags) 的 conn 參數建立與 Service 的聯繫:

public class MainActivity extends AppCompatActivity {

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            DemoService.DemoBinder demoBinder = (DemoService.DemoBinder) service;
            demoBinder.upload();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    public void clickService(View view) {
        switch (view.getId()) {
            case R.id.btn_bind:
                bindService(new Intent(this, DemoService.class), conn, BIND_AUTO_CREATE);
                break;
            case R.id.btn_unbind:
                unbindService(conn);
                break;
        }
    }
}

2. 透過 Intent 傳遞資料

啟動 Service 時把要傳的資料放進 Intent,分別在 onStartCommand() 或 onBind() 中取出,再開新執行緒處理耗時工作。注意兩者的差異:startService() 每次自己都會觸發一次 onStartCommand();bindService() 若已綁定則只會呼叫一次 onBind()。

既然 Service 裡也要開子線程,為何不直接在 Activity 開?因為 Activity 很難控制 Thread:Activity 銷毀後,你再也拿不到先前建立的子線程實例,而且在一個 Activity 建立的子線程,另一個 Activity 也無法操作。Service 則不同,所有 Activity 都能與它關聯、操作其中的方法;即使 Activity 被銷毀,重新關聯後仍能取得原本 Binder 的實例。用 Service 承接後台任務,Activity 就能安心 finish。

3. 跨進程 Messenger 通訊

需要跨進程溝通時,用 Messenger 就能搞定,不必撰寫 AIDL 檔。以下範例中,Service 在綁定時把 Messenger 送給內部的 Handler。

public class MessengerService extends Service {

    private static final String TAG = "MessengerService";
    private NotificationManager mNM;

    /** 快取所有註冊到這個 Service 的 client */
    private final ArrayList<Messenger> mClients = new ArrayList<>();

    private int mValue = 0;

    static final int MSG_REGISTER_CLIENT = 1;
    static final int MSG_UNREGISTER_CLIENT = 2;
    static final int MSG_SET_VALUE = 3;

    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_REGISTER_CLIENT:
                    mClients.add(msg.replyTo);
                    break;
                case MSG_UNREGISTER_CLIENT:
                    mClients.remove(msg.replyTo);
                    break;
                case MSG_SET_VALUE:
                    mValue = msg.arg1;
                    Log.d(TAG, "handleMessage: " + mValue);
                    for (int i = mClients.size() - 1; i >= 0; i--) {
                        try {
                            mClients.get(i).send(
                                    Message.obtain(null, MSG_SET_VALUE, mValue, 0));
                        } catch (RemoteException e) {
                            // client 已關閉,倒序遍歷時刪除是安全的
                            mClients.remove(i);
                        }
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    final Messenger mMessenger = new Messenger(new IncomingHandler());

    @Override
    public void onCreate() {
        super.onCreate();
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        showNotification();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mNM.cancel(R.string.remote_service_started);
    }

    private void showNotification() {
        CharSequence text = getText(R.string.remote_service_started);
        PendingIntent contentIntent = PendingIntent.getActivity(
                this, 0, new Intent(this, ContentActivity.class), 0);
        Notification notification = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setTicker(text)
                .setWhen(System.currentTimeMillis())
                .setContentTitle(getText(R.string.local_service_label))
                .setContentText(text)
                .setContentIntent(contentIntent)
                .getNotification();
        mNM.notify(R.string.remote_service_started, notification);
    }
}

若希望它跑在另一個進程,在清單檔設定 android:process:

<service
    android:name=".app.MessengerService"
    android:process=":remote" />

client 端的寫法:

Messenger mService = null;
boolean mIsBound;

class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MessengerService.MSG_SET_VALUE:
                Log.d(TAG, "handleMessage: " + msg.arg1);
                break;
            default:
                super.handleMessage(msg);
        }
    }
}

final Messenger mMessenger = new Messenger(new IncomingHandler());

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        mService = new Messenger(service);
        try {
            Message msg = Message.obtain(null, MessengerService.MSG_REGISTER_CLIENT);
            msg.replyTo = mMessenger;
            mService.send(msg);

            msg = Message.obtain(null, MessengerService.MSG_SET_VALUE, 202, 0);
            mService.send(msg);
        } catch (RemoteException e) {
            // Service 已崩潰,無需額外處理
        }
    }

    public void onServiceDisconnected(ComponentName className) {
        mService = null;
    }
};

void doBindService() {
    bindService(new Intent(this, MessengerService.class), mConnection, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

void doUnbindService() {
    if (mIsBound) {
        if (mService != null) {
            try {
                Message msg = Message.obtain(null, MessengerService.MSG_UNREGISTER_CLIENT);
                msg.replyTo = mMessenger;
                mService.send(msg);
            } catch (RemoteException e) {
                // 忽略
            }
        }
        unbindService(mConnection);
        mIsBound = false;
    }
}

前台 Service(Foreground Service)

Foreground Service 並不是「跑在前台」,它其實一直在後台,只是透過一個常駐通知讓使用者知道它正在運行。這也是官方推薦的做法:Service 啟動時發一個通知,例如後台播放音樂時狀態欄顯示的播放資訊。

除了自己發通知,Android 2.0(SDK level 5)以上也提供了更直接的 API:

/**
 * 讓 Service 成為 Foreground Service,並產生一個「正在運行」的通知。
 * 預設的 Service 是後台性質,系統在回收記憶體時可以毫無顧忌地將它 kill 掉。
 * 若這個 Service 掛掉會影響使用者(例如後台音樂播放器),就該用 Foreground Service 提示。
 *
 * @param id           通知識別碼,對應 NotificationManager.notify(int, Notification)
 * @param notification 要顯示的通知
 */
public final void startForeground(int id, Notification notification)

/**
 * 取消 foreground 屬性,允許 Service 在低記憶體時被 kill。
 *
 * @param removeNotification 是否同時移除先前提供給 startForeground 的通知
 */
public final void stopForeground(boolean removeNotification)

呼叫 stopForeground() 會把 Service 移出前台,它的 boolean 參數決定是否也把狀態欄通知移除。這個方法本身不會停掉 Service;但反過來說,如果你停止一個正在前台運行的 Service,通知也會一起被刪除。

IntentService:懶得自己開線程就用它

Service 跑在主線程,所以耗時操作還是要自己開子線程。IntentService 是 Service 的子類別,它自帶一個工作執行緒,把每個啟動請求排進佇列,一次處理一個。

用法很簡單:繼承 IntentService,實作 onHandleIntent(),這個方法接收每次啟動請求的 Intent,而且它本身就跑在子線程。

IntentService 以佇列方式排入請求,再開一個 worker thread 依序處理。每個請求都在獨立的 worker thread 中完成,不會阻塞主線程。因此,如果手上有耗時任務,用 IntentService 往往比在 Service 裡自己開新線程更省事——預設的 worker thread 已經幫你實作好了。

使用時要留意四點:

  1. 不能直接與 UI 互動,執行結果必須回傳給 Activity 才能呈現在畫面上。
  2. 任務佇列是順序執行的,新送進來的任務必須等前一個做完才會開始。
  3. 正在執行的任務無法中斷。
  4. 它天生適合「一次性的、可排隊的」背景工作,不適合需要長期運行或即時互動的場景。

遠程 Service

當 Service 需要與其他應用或跨進程溝通時,就是遠程 Service 的場景。實作上可以透過 android:process 把 Service 放到獨立進程,再用 Messenger 或 AIDL 建立通訊介面。這也是為什麼前面特別強調「Service 預設不是獨立進程」——一旦跨進程,資料傳遞、生命週期與效能成本都要重新評估。

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