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

Service 基礎回顧:兩種啟動方式的差別一次講透

編輯:關於 Android 程式設計

Service 是 Android 四大元件裡跟 Activity 個性最接近的一個:有自己的生命週期,創建與配置方式幾乎一致,同樣繼承自 Context,所以 getResources()、getContentResolver() 這些方法都能用。差別只在於它沒有華麗的介面,長期在後台默默做事。

開發 Service 的兩個步驟

  1. 定義一個繼承 Service 的子類。
  2. 在 AndroidManifest.xml 中註冊它。

先熟悉生命週期回呼:

  • IBinder onBind(Intent):必須實作,回傳的 IBinder 是外部與 Service 通訊的橋樑。
  • void onCreate():第一次創建時立刻回呼。
  • int onStartCommand(Intent, int, int):每次呼叫 startService() 都會回呼(早期版本是 onStart)。
  • void onDestroy():Service 被關閉之前回呼。
  • boolean onUnbind(Intent):所有綁定的客戶端都斷線時回呼。
public class MyService extends Service {
    public static final String TAG = MyService.class.getSimpleName();

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

    @Override
    public void onCreate() {
        super.onCreate();
        Log.v(TAG, "onCreate() executed");
        Log.v(TAG, "MyService thread id is " + Thread.currentThread().getId());
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v(TAG, "onDestroy() executed");
    }
}

註冊方式與 Activity 幾乎相同,只是標籤換成 service:

<service android:name=".MyService" />

方式一:startService()

這種啟動方式下,呼叫者與 Service 之間沒有羈絆,Activity 關掉了 Service 依然運行。

case R.id.start_service:
    startService(new Intent(this, MyService.class));
    break;
case R.id.stop_service:
    stopService(new Intent(this, MyService.class));
    break;

先按 Start Service 再按 Stop Service,log 如下:

不關閉服務的情況下連按三次 Start Service:

由此可以驗證一個關鍵結論:onCreate() 只在 Service 第一次被創建時回呼一次,之後無論呼叫多少次 startService,它都不會再執行;但 onStartCommand() 每次啟動都會執行。

方式二:bindService()

這種方式下 Service 與呼叫者綁在一起,呼叫者退出,Service 隨之終止,而且雙向通訊成為可能。先改造 MyService,透過 onBind 把 Binder 交出去:

public class MyService extends Service {
    public static final String TAG = MyService.class.getSimpleName();
    private MyBinder mBinder = new MyBinder();

    @Override
    public IBinder onBind(Intent intent) {
        Log.v(TAG, "onBind() executed");
        return mBinder;
    }

    // onCreate / onStartCommand / onDestroy 同上

    class MyBinder extends Binder {
        public void startDownload() {
            Log.v(TAG, "startDownload() executed");
        }
    }
}

bindService 的三個參數:

  • service:以 Intent 指定要啟動哪個 Service。
  • conn:ServiceConnection 物件,用來監聽連接狀態。連接成功回呼 onServiceConnected(ComponentName, IBinder);Service 所在進程異常終止導致斷線時回呼 onServiceDisconnected(ComponentName)。注意:如果是呼叫端主動 unbindService() 切斷,onServiceDisconnected 不會被觸發。
  • flags:是否自動創建 Service,0 表示不創建,BIND_AUTO_CREATE 表示自動創建。
private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        myBinder = (MyBinder) service;
        myBinder.startDownload();   // 透過 Binder 直接呼叫 Service 的方法
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.v(TAG, "onServiceDisconnected() " + name);
    }
};

case R.id.bind_service:
    bindService(new Intent(this, MyService.class), connection, BIND_AUTO_CREATE);
    break;
case R.id.unbind_service:
    unbindService(connection);
    break;

按 Bind Service 再按 unBind Service 的結果:

可以看到 MainActivity 已成功呼叫到 MyService 的 startDownload(),通訊建立。

通訊是怎麼發生的

當你呼叫 bindService 把兩者綁定後,MyService 的 onBind() 所回傳的 IBinder 會被系統送進 MainActivity 的 onServiceConnected(ComponentName name, IBinder service) 的 service 參數。之後 Activity 只要轉型成自訂的 Binder 子類,就能直接呼叫 Service 暴露的方法。這也是 AIDL 跨進程通訊的基礎縮影。

一個容易忽略的細節

用 startService 啟動會走 onStartCommand,用 bindService 啟動卻不會。原因是兩種方式下 Service 的生命週期路徑不同:前者是 onCreate → onStartCommand → onDestroy;後者是 onCreate → onBind → onUnbind → onDestroy。兩者可以混用,此時 Service 會一直存活到 stopService 與所有 unbind 都發生為止。

另外提醒:Service 預設跑在呼叫它的主進程主線程上,onCreate() 或 onStartCommand() 裡寫耗時邏輯一樣會 ANR。需要真正卸重,請自己開線程,或直接用 IntentService / JobIntentService。

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