AIDL通信过程中设置死亡代理

关于AIDL的使用参考学习:

https://blog.csdn.net/u011240877/article/details/72765136

https://blog.csdn.net/iromkoear/article/details/59706441

关于设置死亡代理:

在进行进程间通信的过程中,如果服务端进程由于某种原因异常终止,我们的远程调用就会失败,影响我们的功能,那么怎么样能够知道服务端进程是否终止了呢,一种方法就是给Binder设置死亡代理。

方法是在onServiceConnected()函数中,

mBookManager.asBinder().linkToDeath(mDeathRecipient,0);//mBookManager为服务端进行的Service对象,通过asBinder()可以获得Binder对象

另外定义死亡代理对象

private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
     @Override
     public void binderDied() {
         if (mBookManager == null) return;
         mBookManager.asBinder().unlinkToDeath(mDeathRecipient,0);//解除死亡通知,如果Binder死亡了,不会在触发binderDied方法
         mBookManager = null;
     }
};

如果服务端进程死亡了,会回调到binderDied()函数

后面通过判断mBookManager是否为null即可知道服务端进程是否死亡

除设置死亡代理,Binder对象还有两个方法可以判断服务器进行是否存在或存活,返回均为boolean类型

mBookManager.asBinder().pingBinder();
mBookManager.asBinder().isBinderAlive();
     /**//检查Binder对象是否存在
     * Check to see if the object still exists.
     * 
     * @return Returns false if the
     * hosting process is gone, otherwise the result (always by default
     * true) returned by the pingBinder() implementation on the other
     * side.
     */
    public boolean pingBinder();

    /**//检查Binder所在的进程是否存活
     * Check to see if the process that the binder is in is still alive.
     *
     * @return false if the process is not alive.  Note that if it returns
     * true, the process may have died while the call is returning.
     */
    public boolean isBinderAlive();

参考https://blog.csdn.net/small_lee/article/details/79181985

原文地址:https://www.cnblogs.com/genggeng/p/9810322.html