這個綁定是異步的,bindService()方法立即返回,並且不給客戶端返回IBinder對象。要接收IBinder對象,客戶端必須創建一個ServiceConnection類的實例,並且把這個實例傳遞給bindService()方法。ServiceConnection對象包含了一個系統調用的傳遞IBinder對象的回調方法。
注意:只有Activity、Service、和內容提供器(content provider)能夠綁定服務---對於廣播接收器不能綁定服務。
因此,要在客戶端綁定一個服務,必須做以下事情:
1. 實現ServiceConnection抽象類
你的實現必須重寫以下兩個回調方法:
onServiceConnected()
系統會調用這個方法來發送由服務的onBind()方法返回的IBinder對象。
onServiceDisconnected()
Android系統會在連接的服務突然丟失的時候調用這個方法,如服務崩潰時或被殺死時。在客戶端解除服務綁定時不會調用這個方法。
2. 調用bindService()方法來傳遞ServiceConnection類的實現;
3. 當系統調用你的onServiceConnected()回調方法時,你就可以開始使用接口中定義的方法來調用服務了;
4. 調用unbindService()方法斷開與服務的連接。
當客戶端銷燬時,它將於服務端解綁,但是當你完成與服務端的交互或Activity暫停時,你應該主動的與服務端解綁,以便服務能夠在不使用的時候關掉。(綁定和解綁的時機會在稍後進行更多的討論)。
例如,以下代碼片段演示了把客戶端連接到由繼承Binder類創建服務,它所做的所有事情就是把服務端返回的IBinder對象轉換成LocalService類,並且請求LocalService實例:
LocalService mService;
private ServiceConnection mConnection = new ServiceConnection() {
// Called when the connection with the service is established
public void onServiceConnected(ComponentName className, IBinder service) {
// Because we have bound to an explicit
// service that is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
// Called when the connection with the service disconnects unexpectedly
public void onServiceDisconnected(ComponentName className) {
Log.e(TAG, "onServiceDisconnected");
mBound = false;
}
};
用這個ServiceConnection類,客戶端能夠把它傳遞給bindService()方法來實現與服務端的綁定,如:
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
1. bindService方法的第一個參數是一個Intent對象,它明確的命名要綁定的服務(雖然Intent能夠隱含的指定);
2. 第二個參數是ServiceConnection對象;
3. 第三個參數是指明綁定選項的標識。通常它應該使用BIND_AUTO_CREATE,以便在服務不存在的時候創建這個服務。其他可能的值是BIND_DEBUG_UNBIND和BIND_NOT_FOREGROUND,或是什麼都沒有的“0”。