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调用结束


更多详情使用:例子链接






更多相关文章

  1. Android接口测试-JUnit入门
  2. 最简单android的下拉列表_基础篇
  3. Android LCD(三):Samsung LCD接口篇
  4. Android Framework Display/Framework和C++语法个人文章列表整理
  5. Android - 信息列表页面【仿】淘宝App
  6. android折叠展开列表测试
  7. android之PopUpWindow显示Listview(文件列表)

随机推荐

  1. 更新:在Gulpfile中带有postCSS和Babel的
  2. 推json敲出可观察的数组
  3. Angularjs在ng-repeat中找到最后一个可见
  4. Angularjs:如何将范围变量传递给指令?
  5. IE 浏览器各个版本 JavaScript 支持情况
  6. 当页面上有多个按钮时,按钮样式在页面加载
  7. 从占用转义字符的字符数组创建字符串
  8. 无法让.click()在禁用的textarea上工作
  9. AJAX应该使用hashtag /#!/或不呢?
  10. Div高度为图像高度,图像宽度为div宽度