android 之 linkToDeath和unlinkToDeath。(死亡代理)

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);  

  
    }  
}  

  • 6
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值