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

你可能感兴趣的:(android,开发)