Binder死亡代理
我们都知道,在和service进行交互时,service返回一个Binder对象。Binder是工作在service端,如果,由于某种原因,服务端出现故障而死亡,那么该返回的Binder对象也将消失,这时,如果我们在客户端在使用Binder对象进行某些函数调用将会出现错误。为了避免该情况的发生,我们可以为Binder对象设置死亡代理。当出现和服务端连接发生故障时,系统将自动调用死亡代理函数binderDied()。
死亡代理是由DeathRecipient 来实现,使用它比较简单,只要重写里面的binderDied()方法即可。
linkToDeath():为Binder对象设置死亡代理。
unlinkToDeath():将设置的死亡代理标志清除。
实例代码(参考网上的其它代码):
public class MainActivity extends Activity { private IAidlCall mIAidlCall; private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() { @Override public void binderDied() { // TODO Auto-generated method stub if (mIAidlCall == null) return; mIAidlCall.asBinder().unlinkToDeath(mDeathRecipient, 0); mIAidlCall = null; // TODO:重新绑定远程服务
bindService(new Intent("demo.action.aidl.IAidlCall").
setPackage("com.example.severdemo"), conn, BIND_AUTO_CREATE);
} }; private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { mIAidlCall = IAidlCall.Stub.asInterface(service); try { service.linkToDeath(mDeathRecipient, 0); Toast.makeText(getApplicationContext(), mIAidlCall.getName(), Toast.LENGTH_LONG).show(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // "demo.action.aidl.IAidlCall" 是远程服务的action bindService(new Intent("demo.action.aidl.IAidlCall")
.setPackage("com.example.severdemo"), conn, BIND_AUTO_CREATE);} }