日拱一卒(二十一)

Android RemoteCallbackList:

先来看下Android官网对RemoteCallbackList的说明:

Takes care of the grunt work of maintaining a list of remote interfaces, typically for the use of performing callbacks from aService to its clients. In particular, this:

  • Keeps track of a set of registered IInterface callbacks, taking care to identify them through their underlying uniqueIBinder (by calling IInterface.asBinder().
  • Attaches a IBinder.DeathRecipient to each registered interface, so that it can be cleaned out of the list if its process goes away.
  • Performs locking of the underlying list of interfaces to deal with multithreaded incoming calls, and a thread-safe way to iterate over a snapshot of the list without holding its lock.

To use this class, simply create a single instance along with your service, and call itsregister(E) and unregister(E) methods as client register and unregister with your service. To call back on to the registered clients, usebeginBroadcast(), getBroadcastItem(int), andfinishBroadcast().

If a registered callback's process goes away, this class will take care of automatically removing it from the list. If you want to do additional work in this situation, you can create a subclass that implements theonCallbackDied(E) method.

上面主要说明了:

     (1)RemoteCallbackList用来保存Service的监听器的列表,通常如果service要调用Activity的方法,可以通过一个AIDL定义一个接口,将这个接口加到RemoteCallbackList中,在Service需要调用Activity代码中取出RemoteCallbackList中合适的接口调用。

     (2)如果远程进程结束,那么放在RemoteCallbackList的接口会被移除。如果想在移除时候做善后工作,实现onCallbackDied(E)方法

     (3) 通过接口list加锁的方式处理多线程调用,在没有获得锁情况下以一种线程安全的方式遍历这个列表的拷贝。

使用:
     (1)定义AIDL接口:新建aidl文件和实现aidl接口

     (2)注册:创建一个Service,用register(E)注册一个对Service的监听器;unregister(E)反注册一个对Service的监听器。

     (3)调用:用到三个方法:beginBroadcast(),getBroadcastItem(int), and finishBroadcast().

int i = callbacks.beginBroadcast();
 while (i > 0) {
     i--;
     try {
         callbacks.getBroadcastItem(i).somethingHappened();
     } catch (RemoteException e) {
         // The RemoteCallbackList will take care of removing
         // the dead object for us.
     }
 }
 callbacks.finishBroadcast();

注:

beginBroadcast:拷贝回调列表,返回列表的个数

getBroadcastItem:取出回调列表中接口对象

finishBroadcast:标志RemoteCallbackLis调用结束


更多详情使用:例子链接






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值