1.Binder死亡代理
这一节首先将介绍Binder类中比较重要的两个方法
linkToDeath和
unlinkToDeath。我们知道Binder是运行在服务进程,若服务端进程因为某种原因“死亡”,那么Binder对象也将随之而去,因为Binder对象是寄宿在服务端进程中的,这个时候我们的远程调用将会失败,客户端进程的功能也将受到影响。Binder类提供
linkToDeath方法在客户端可以设置死亡代理,当服务端的Binder对象“死亡”,客户端可以受到死亡通知,这个时候我们可以重新恢复链接。
1.1 linkToDeath方法源码释义。
/**
* Register the recipient for a notification if this binder
* goes away. If this binder object unexpectedly goes away
* (typically because its hosting process has been killed),
* then the given {@link DeathRecipient}'s
* {@link DeathRecipient#binderDied DeathRecipient.binderDied()} method
* will be called.
*
* <p>You will only receive death notifications for remote binders,
* as local binders by definition can't die without you dying as well.
*
* @throws RemoteException if the target IBinder's
* process has already died.
*
* @see #unlinkToDeath
*/
public void linkToDeath(DeathRecipient recipient, int flags)
throws RemoteException;
如果Binder死亡,那么该方法会注册一个通知的接受者。若binder对象意外死亡(一个典型的例子就是宿主进程被系统回收),那么死亡代理
DeathRecipient
的
binderDied()
方法将被调用。另外注意,你只会收到远程binder对象的死亡通知,本地的binder对象是不会收到的。
2.
unlinkToDeath方法源码释义。
/**
* Remove a previously registered death notification.
* The recipient will no longer be called if this object
* dies.
*
* @return {@code true} if the <var>recipient</var> is successfully
* unlinked, assuring you that its
* {@link DeathRecipient#binderDied DeathRecipient.binderDied()} method
* will not be called; {@code false} if the target IBinder has already
* died, meaning the method has been (or soon will be) called.
*
* @throws java.util.NoSuchElementException if the given
* <var>recipient</var> has not been registered with the IBinder, and
* the IBinder is still alive. Note that if the <var>recipient</var>
* was never registered, but the IBinder has already died, then this
* exception will <em>not</em> be thrown, and you will receive a false
* return value instead.
*/
public boolean unlinkToDeath(DeathRecipient recipient, int flags);
该方法的作用是移除先前注册的死亡通知,如果binder对象死亡,那么死亡接受者将不再被调用。
1)方法返回true:如果死亡接受者已经成功断开,要确保其
binderDied()方法不会再被调用。
2)方法返回false:如果目标IBinder对象已经死亡,意味着
binderDied()方法已经(或者不久之后)被调用。
1.2.linkToDeath和unlinkToDeath使用
在客户端代码如下。
public class MainActivity extends Activity {
private IAidlCall mIAidlCall;
private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
@Override
public void binderDied() {