IPC 设置死亡代理
2020-05-05 本文已影响0人
静享时光
Binder是可能以外死亡的,这往往是由于服务端进程意外停止了,这是我们需要重新连接服务。有两种方法。
方法一
第一种方法时给Binder设置DeathReciient监听,当Binder死亡是,我们就会受到binderDied方法的回调,在binderDied方法中我们可以重连远程服务。
需要在Activity中进行修改
/**
* 设置死亡代理
*/
private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
@Override
public void binderDied() {
if (iBookManager == null) {
return;
}
iBookManager.asBinder().unlinkToDeath(mDeathRecipient, 0);
iBookManager = null;
//重新绑定服务
bindMyService();
}
};
/**
* 绑定服务
*/
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 {
//设置死亡代理
iBookManager.asBinder().linkToDeath(mDeathRecipient, 0);
//注册监听
iBookManager.registerListener(iOnNewBookArrvedListener);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
iBookManager = null;
}
};
bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
方法二
在onServiceDisconnected方法中重连远程服务
两种方法的区别
onServiceDisconnected运行在ui线程中被回调,而binderDied在客户端的Binder线程池中被回调。所以在binderDied方法中不能访问UI。