Android开发艺术探索学习-IPC之Binder(二)

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() {
	
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值