Android进程间通信之AIDL(三)—— deadObject异常处理

由于客户端是通过bindService绑定服务端的service,而Android系统运行环境复杂,服务随时都可能被kill,如果此时再次调用服务端的接口,会引起deadObject异常的发生。

解决办法

一、使用之前先判断bind是否还存活

if (mIMyAidlInterface != null && mIMyAidlInterface.asBinder().isBinderAlive()) {
    try {
        mIMyAidlInterface.getWorker(new Worker("worker_1", 0, "get"));
    } catch (Exception e) {
        Log.e(TAG, "Exception");
        //
        e.printStackTrace();
    }
}

二、注册死亡代理

首先定义一个DeathRecipient 类

private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {

    @Override
    public void binderDied() {                  // 当绑定的service异常断开连接后,会自动执行此方法
        Log.e(TAG,"enter Service binderDied " );
        if (mIMyAidlInterface != null){
            mIMyAidlInterface.asBinder().unlinkToDeath(mDeathRecipient, 0);
            bindService(new Intent("com.service.bind"),mMyServiceConnection,BIND_AUTO_CREATE);      //  重新绑定服务端的service
        }
    }
};

然后在service绑定成功后,调用linkToDeath()注册进service,当service发生异常断开连接后会自动调用binderDied(),处理异常

public void onServiceConnected(ComponentName name, IBinder service) {           //绑定成功回调
    Log.d(TAG, "onServiceConnected");
    mIMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);     //获取服务端提供的接口
    try {
        service.linkToDeath(mDeathRecipient, 0);        // 注册死亡代理
        Log.d(TAG, mIMyAidlInterface.getName());
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值