Binder是可能以外死亡的,這往往是由于服務(wù)端進程意外停止了,這是我們需要重新連接服務(wù)。有兩種方法。
方法一
第一種方法時給Binder設(shè)置DeathReciient監(jiān)聽,當Binder死亡是,我們就會受到binderDied方法的回調(diào),在binderDied方法中我們可以重連遠程服務(wù)。
需要在Activity中進行修改
/**
* 設(shè)置死亡代理
*/
private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
@Override
public void binderDied() {
if (iBookManager == null) {
return;
}
iBookManager.asBinder().unlinkToDeath(mDeathRecipient, 0);
iBookManager = null;
//重新綁定服務(wù)
bindMyService();
}
};
/**
* 綁定服務(wù)
*/
private void bindMyService() {
Intent serviceIntent = new Intent(this, BookManagerService.class);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iBookManager = IBookManager.Stub.asInterface(service);
try {
//設(shè)置死亡代理
iBookManager.asBinder().linkToDeath(mDeathRecipient, 0);
//注冊監(jiān)聽
iBookManager.registerListener(iOnNewBookArrvedListener);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
iBookManager = null;
}
};
bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
方法二
在onServiceDisconnected方法中重連遠程服務(wù)
兩種方法的區(qū)別
onServiceDisconnected運行在ui線程中被回調(diào),而binderDied在客戶端的Binder線程池中被回調(diào)。所以在binderDied方法中不能訪問UI。