HanteIsHante / file

file note
4 stars 0 forks source link

Service AIDL 发生DeadObjectException #61

Closed HanteIsHante closed 5 years ago

HanteIsHante commented 5 years ago
Caused by android.os.DeadObjectException
       at android.os.BinderProxy.transactNative(Binder.java)
       at android.os.BinderProxy.transact(Binder.java:748)
       at packageName$Stub$Proxy.getState(IProxyService.java:138)
       at packageName.BaseActivity.onServiceConnected(BaseActivity.kt:75)
HanteIsHante commented 5 years ago

参考 CSDN

首先定义一个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
        }
    }
};
--------------------- 
作者:zhfdzh 
来源:CSDN 
原文:https://blog.csdn.net/qq_26643587/article/details/80237582 

然后在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();
    }
}
--------------------- 
作者:zhfdzh 
来源:CSDN 
原文:https://blog.csdn.net/qq_26643587/article/details/80237582 
HanteIsHante commented 5 years ago

可能还会产生这个问题,可以添加上 try...catch..