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

Android AIDL Service 綁定的實作步驟

編輯:關於 Android 開發

使用 bindService 方法來綁定服務的具體步驟如下:

一、以 bindService 啟動服務

bindService(Intent service, ServiceConnection conn, int flags) 有三個參數。其中第二個參數 ServiceConnection 與最後一個標識參數較為陌生:呼叫 bindService 時需要一個 ServiceConnection 來取得服務實例與狀態,程式碼如下:

private ServiceConnection sc = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Toast.makeText(ctx, "android123 service connected", Toast.LENGTH_LONG).show();
    }
    @Override
    public void onServiceDisconnected(ComponentName name) {
        Toast.makeText(ctx, "android123 service disconnected", Toast.LENGTH_LONG).show();
    }
};

如此一來,不論是服務連線還是斷開,都會收到 Toast 訊息提示。bindService 的最後一個參數一般使用 BIND_AUTO_CREATE 標識來自動建立服務,因此綁定服務通常寫成:

bindService(intent, sc, Service.BIND_AUTO_CREATE);

解除綁定則使用 unbindService(sc);。

二、Service 端需要處理的內容

以下三個方法在綁定流程中扮演重要角色:

public boolean onUnbind(Intent intent) // 反綁定服務時做清理工作
public void onRebind(Intent intent) // 重新綁定時觸發
public abstract IBinder onBind(Intent intent) // 需要回傳一個 IBinder 物件,因此必須實作此抽象方法

三、實作 onBind 方法

這裡我們簡單地為服務的呼叫者傳遞一個 Service 的實例:

public class cwjBinder extends Binder {
    cwjService fetchService() {
        return cwjService.this;
    }
}

在建立 Service 時實例化 cwjBinder(例如 cwjBinder binderObj = new cwjBinder();),此時 onBind() 的回傳值便設定為 binderObj,而非 null。

四、回到呼叫端取得服務實例

回到呼叫 Service 的地方,在 ServiceConnection 的 onServiceConnected 方法中,第二個參數就是我們剛才的 IBinder 實例。該方法的原型為 public void onServiceConnected(ComponentName name, IBinder service),此時我們便能呼叫 fetchService 方法,取得 Service 實例並進行後續操作。

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