使用IBinder的linkToDeath机制来释放资源

    The linkToDeath() method can be used to register a IBinder.DeathRecipient with the IBinder, which will be called when its containing process goes away.

就是说我们通过systemService申请了某个service的Binder后,可以调用这个IBinder的linkToDeath函数进行注册。可以注册一个IBinder.DeathRecipient类型的对象。其中IBinder.DeathRecipient是IBinder类中定义的一个嵌入类。

public abstract void linkToDeath (IBinder.DeathRecipient recipient, int flags)

Added in  API level 1

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 IBinder.DeathRecipient's DeathRecipient.binderDied() method will be called.

You will only receive death notifications for remote binders, as local binders by definition can't die without you dying as well.

当这个IBinder所对应的Service进程被异常的退出时,比如被kill掉,这时系统会调用这个IBinder之前通过linkToDeath注册的DeathRecipient类对象的binderDied函数。

一般实现中,Bp端会注册linkToDeath,目的是为了监听绑定的Service的异常退出,一般的binderDied函数的实现是用来释放一些相关的资源。

public abstract boolean unlinkToDeath (IBinder.DeathRecipient recipient, int flags)

Added in  API level 1

Remove a previously registered death notification. The recipient will no longer be called if this object dies.

可以在Server端(我写的程序中Server端是个一直在系统中运行的Service)中按照如下方式实现DeathHandler,然后在应用程序部分调用notifyProcessDied(new Binder())就可以了。

附Server端的DeathHandler实现。


public boolean notifyProcessDied(IBinder cb){
        MyServiceDeathHandler deathHandler = new MyServiceDeathHandler(cb);
        try {
            cb.linkToDeath(deathHandler, 0);
        } catch (RemoteException e) {
            return false;
        }
        return true;
    }
    
    private class MyServiceDeathHandler implements IBinder.DeathRecipient {
        private IBinder mCb;
        public MyServiceDeathHandler(IBinder Cb) {
            mCb = Cb;
        }
        @Override
        public void binderDied() {
            // release resource when host process died.     
        }
        public IBinder getBinder() {
            return mCb;
        }    
    }





至于unlinkToDeath()方法的使用我这边并没有举例具体可以参考AudioManager和AudioService的实现。

其中AudioService是一个Server端,每个程序都有一个AudioManager,AudioManage是一个Client端。

由于应用程序进程被杀死的时候,AudioService需要释放一些资源。所以使用了IBinder的linkToDeath机制来释放一些资源。


你可能感兴趣的:(使用IBinder的linkToDeath机制来释放资源)