一、Android应用程序注冊广播接收器(registerReceiver)的过程分析

參考Android应用程序注冊广播接收器(registerReceiver)的过程分析http://blog.csdn.net/luoshengyang/article/details/6737352和《Android系统源码情景分析》,作者罗升阳。

0、总图:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamx0eGdjeQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />

1、MainActivity和CounterService所在应用程序主线程向ActivityManagerService进程发送REGISTER_RECEIVER_TRANSACTION

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamx0eGdjeQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />

如图:第一步

~/Android/frameworks/base/core/java/android/app

----ActivityManagerNative.java

  1. class ActivityManagerProxy implements IActivityManager
  2. {
  3. ......
  4.  
  5. public Intent registerReceiver(IApplicationThread caller,
  6. IIntentReceiver receiver,
  7. IntentFilter filter, String perm) throws RemoteException
  8. {
  9. Parcel data = Parcel.obtain();
  10. Parcel reply = Parcel.obtain();
  11. data.writeInterfaceToken(IActivityManager.descriptor);
  12. data.writeStrongBinder(caller != null ? caller.asBinder() : null);
  13. data.writeStrongBinder(receiver != null ? receiver.asBinder() : null);
  14. filter.writeToParcel(data, 0);
  15. data.writeString(perm);
  16. mRemote.transact(REGISTER_RECEIVER_TRANSACTION, data, reply, 0);
  17. reply.readException();
  18. Intent intent = null;
  19. int haveIntent = reply.readInt();
  20. if (haveIntent != 0) {
  21. intent = Intent.CREATOR.createFromParcel(reply);
  22. }
  23. reply.recycle();
  24. data.recycle();
  25. return intent;
  26. }
  27.  
  28. ......
  29.  
  30. }

当中receiver为InnerReceiver对象,例如以下图。还要filter,主要关注这两个參数。

如图:第二步,省略binder_transaction传输过程,由于上面已经分析过了。

如图:第三步

~/Android/frameworks/base/core/java/android/app

----ActivityManagerNative.java

  1. public abstract class ActivityManagerNative extends Binder implements IActivityManager
  2. {
  3. ......
  4. public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
  5. throws RemoteException {
  6. switch (code) {
  7. case REGISTER_RECEIVER_TRANSACTION:
  8. {
  9. data.enforceInterface(IActivityManager.descriptor);
  10. IBinder b = data.readStrongBinder();
  11. IApplicationThread app =
  12. b != null ?
  13.  
  14. ApplicationThreadNative.asInterface(b) : null;
  15. b = data.readStrongBinder();
  16. IIntentReceiver rec
  17. = b != null ? IIntentReceiver.Stub.asInterface(b) : null;
  18. IntentFilter filter = IntentFilter.CREATOR.createFromParcel(data);
  19. String perm = data.readString();
  20. Intent intent = registerReceiver(app, rec, filter, perm);
  21. reply.writeNoException();
  22. if (intent != null) {
  23. reply.writeInt(1);
  24. intent.writeToParcel(reply, 0);
  25. } else {
  26. reply.writeInt(0);
  27. }
  28. return true;
  29. }
  30. .......
  31. }

rec为IIntentReceiver.Stub.Proxy对象,如上图所看到的。还要filter,主要关注这两个參数。

如图:第四步

~/Android/frameworks/base/services/java/com/android/server/am

----ActivityManagerService.java

  1. public final class ActivityManagerService extends ActivityManagerNative
  2. implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
  3. ......
  4.  
  5. public Intent registerReceiver(IApplicationThread caller,
  6. IIntentReceiver receiver, IntentFilter filter, String permission) {
  7. synchronized(this) {
  8. ProcessRecord callerApp = null;
  9. if (caller != null) {
  10. callerApp = getRecordForAppLocked(caller);
  11. if (callerApp == null) {
  12. ......
  13. }
  14. }
  15.  
  16. .......
  17. ReceiverList rl
  18. = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
  19. if (rl == null) {
  20. rl = new ReceiverList(this, callerApp,
  21. Binder.getCallingPid(),
  22. Binder.getCallingUid(), receiver);
  23.  
  24. if (rl.app != null) {
  25. rl.app.receivers.add(rl);
  26. } else {
  27. ......
  28. }
  29. mRegisteredReceivers.put(receiver.asBinder(), rl);
  30. }
  31.  
  32. BroadcastFilter bf = new BroadcastFilter(filter, rl, permission);
  33. rl.add(bf);
  34. ......
  35. mReceiverResolver.addFilter(bf);
  36.  
  37. // Enqueue broadcasts for all existing stickies that match
  38. // this filter.
  39. if (allSticky != null) {
  40. ......
  41. }
  42.  
  43. return sticky;
  44. }
  45. }
  46.  
  47. ......
  48.  
  49. }

主要做了下面几件事:

(1)依据receiver创建ReceiverList。

(2)依据filter和rl创建BroadcastFilter。

(3)mReceiver.addFilter(bf)。

二、Android应用程序发送广播(sendBroadcast)的过程分析

0、总图

1、MainActivity和CounterService所在应用程序主线程向ActivityManagerService进程发送BROADCAST_INTENT_TRANSACTION

如图:第一步

~/Android/frameworks/base/core/java/android/app

----ActivityManagerNative.java

  1. class ActivityManagerProxy implements IActivityManager
  2. {
  3. ......
  4.  
  5. public int broadcastIntent(IApplicationThread caller,
  6. Intent intent, String resolvedType, IIntentReceiver resultTo,
  7. int resultCode, String resultData, Bundle map,
  8. String requiredPermission, boolean serialized,
  9. boolean sticky) throws RemoteException
  10. {
  11. Parcel data = Parcel.obtain();
  12. Parcel reply = Parcel.obtain();
  13. data.writeInterfaceToken(IActivityManager.descriptor);
  14. data.writeStrongBinder(caller != null ? caller.asBinder() : null);
  15. intent.writeToParcel(data, 0);
  16. data.writeString(resolvedType);
  17. data.writeStrongBinder(resultTo != null ? resultTo.asBinder() : null);
  18. data.writeInt(resultCode);
  19. data.writeString(resultData);
  20. data.writeBundle(map);
  21. data.writeString(requiredPermission);
  22. data.writeInt(serialized ? 1 : 0);
  23. data.writeInt(sticky ? 1 : 0);
  24. mRemote.transact(BROADCAST_INTENT_TRANSACTION, data, reply, 0);
  25. reply.readException();
  26. int res = reply.readInt();
  27. reply.recycle();
  28. data.recycle();
  29. return res;
  30. }
  31.  
  32. ......
  33.  
  34. }

当中主要关注intent參数。

如图:第二步,省略binder_transaction传输过程。由于上面已经分析过了。

如图:第三步

~/Android/frameworks/base/core/java/android/app

----ActivityManagerNative.java

  1. public abstract class ActivityManagerNative extends Binder implements IActivityManager
  2. {
  3. ......
  4. public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
  5. throws RemoteException {
  6. switch (code) {
  7. case BROADCAST_INTENT_TRANSACTION:
  8. {
  9. data.enforceInterface(IActivityManager.descriptor);
  10. IBinder b = data.readStrongBinder();
  11. IApplicationThread app =
  12. b != null ?
  13.  
  14. ApplicationThreadNative.asInterface(b) : null;
  15. Intent intent = Intent.CREATOR.createFromParcel(data);
  16. String resolvedType = data.readString();
  17. b = data.readStrongBinder();
  18. IIntentReceiver resultTo =
  19. b != null ?
  20.  
  21. IIntentReceiver.Stub.asInterface(b) : null;
  22. int resultCode = data.readInt();
  23. String resultData = data.readString();
  24. Bundle resultExtras = data.readBundle();
  25. String perm = data.readString();
  26. boolean serialized = data.readInt() != 0;
  27. boolean sticky = data.readInt() != 0;
  28. int res = broadcastIntent(app, intent, resolvedType, resultTo,
  29. resultCode, resultData, resultExtras, perm,
  30. serialized, sticky);
  31. reply.writeNoException();
  32. reply.writeInt(res);
  33. return true;
  34. }
  35. .......
  36. }

如图:第四步

~/Android/frameworks/base/services/java/com/android/server/am

----ActivityManagerService.java

  1. public final class ActivityManagerService extends ActivityManagerNative
  2. implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
  3. ......
  4.  
  5. public final int broadcastIntent(IApplicationThread caller,
  6. Intent intent, String resolvedType, IIntentReceiver resultTo,
  7. int resultCode, String resultData, Bundle map,
  8. String requiredPermission, boolean serialized, boolean sticky) {
  9. synchronized(this) {
  10. intent = verifyBroadcastLocked(intent);
  11.  
  12. final ProcessRecord callerApp = getRecordForAppLocked(caller);
  13. final int callingPid = Binder.getCallingPid();
  14. final int callingUid = Binder.getCallingUid();
  15. final long origId = Binder.clearCallingIdentity();
  16. int res = broadcastIntentLocked(callerApp,
  17. callerApp != null ? callerApp.info.packageName : null,
  18. intent, resolvedType, resultTo,
  19. resultCode, resultData, map, requiredPermission, serialized,
  20. sticky, callingPid, callingUid);
  21. Binder.restoreCallingIdentity(origId);
  22. return res;
  23. }
  24. }
  25.  
  26. ......
  27. }

主要做了下面几件事:

(1)依据intent找出对应的广播接收器:

  1. List<BroadcastFilter> registeredReceivers = null;
  2. registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);

(2)依据intent(里面还包括数据)。registeredReceivers创建BroadcastRecord对象,并增加mParallelBroadcasts中:

  1. BroadcastRecord r = new BroadcastRecord(intent, callerApp,
  2. callerPackage, callingPid, callingUid, requiredPermission,
  3. registeredReceivers, resultTo, resultCode, resultData, map,
  4. ordered, sticky, false);
  5. mParallelBroadcasts.add(r);

(3)依据r和从r中得到的BroadcastFilter(即上面注冊时的BroadcastFilter),调用deliverToRegisteredReceiverLocked:

  1. deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);

(4)调用filter.receiverList.receiver和new Intent(r.intent)调用performReceiveLocked:

  1. performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
  2. new Intent(r.intent), r.resultCode,
  3. r.resultData, r.resultExtras, r.ordered, r.initialSticky);

(5)ActivityManagerService进程向MainActivity和CounterService所在应用程序子线程发送SCHEDULE_REGISTERED_RECEIVER_TRANSACTION

  1. app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
  2. data, extras, ordered, sticky);

当中receiver为IIntentReceiver.Stub.Proxy对象。intent为要传递的数据。

2、ActivityManagerService进程向MainActivity和CounterService所在应用程序子线程发送SCHEDULE_REGISTERED_RECEIVER_TRANSACTION

如图:第一步

~/Android/frameworks/base/core/java/android/app

----ApplicationThreadNative.java,ApplicationThreadProxy类

  1. class ApplicationThreadProxy implements IApplicationThread {
  2. ......
  3.  
  4. public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
  5. int resultCode, String dataStr, Bundle extras, boolean ordered, boolean sticky)
  6. throws RemoteException {
  7. Parcel data = Parcel.obtain();
  8. data.writeInterfaceToken(IApplicationThread.descriptor);
  9. data.writeStrongBinder(receiver.asBinder());
  10. intent.writeToParcel(data, 0);
  11. data.writeInt(resultCode);
  12. data.writeString(dataStr);
  13. data.writeBundle(extras);
  14. data.writeInt(ordered ?
  15.  
  16. 1 : 0);
  17. data.writeInt(sticky ?
  18.  
  19. 1 : 0);
  20. mRemote.transact(SCHEDULE_REGISTERED_RECEIVER_TRANSACTION, data, null,
  21. IBinder.FLAG_ONEWAY);
  22. data.recycle();
  23. }
  24.  
  25. ......
  26. }

当中receiver为IIntentReceiver.Stub.Proxy对象,intent为要传递的数据。

如图:第二步,省略binder_transaction传输过程,由于上面已经分析过了。

如图:第三步

~/Android/frameworks/base/core/java/android/app

----ApplicationThreadNative.java

  1. public abstract class ApplicationThreadNative extends Binder
  2. implements IApplicationThread {
  3. ........
  4. public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
  5. throws RemoteException {
  6. switch (code) {
  7. case SCHEDULE_REGISTERED_RECEIVER_TRANSACTION: {
  8. data.enforceInterface(IApplicationThread.descriptor);
  9. IIntentReceiver receiver = IIntentReceiver.Stub.asInterface(
  10. data.readStrongBinder());
  11. Intent intent = Intent.CREATOR.createFromParcel(data);
  12. int resultCode = data.readInt();
  13. String dataStr = data.readString();
  14. Bundle extras = data.readBundle();
  15. boolean ordered = data.readInt() != 0;
  16. boolean sticky = data.readInt() != 0;
  17. scheduleRegisteredReceiver(receiver, intent,
  18. resultCode, dataStr, extras, ordered, sticky);
  19. return true;
  20. }
  21. .......
  22. }

当中receiver为InnerReceiver。

intent为要传递的数据。

大家已经对,IIntentReceiver.Stub.asInterface( data.readStrongBinder())非常费解,data.readStrongBinder得到是InnerReceiver对象,那为什么要生成IIntentReceiver.Stub.Proxy的代理对象呢?事实上不然。绕了一圈,最后还是生成了InnerReceiver对象。

  1. public static android.content.IIntentReceiver asInterface(
  2. android.os.IBinder obj) {
  3. if ((obj == null)) {
  4. return null;
  5. }
  6. android.os.IInterface iin = (android.os.IInterface) obj
  7. .queryLocalInterface(DESCRIPTOR);//假设是BinderProxy对象调用这种方法。返回的NULL。可是如今是InnerReceiver,详细调用例如以下,返回的是IInterface
  8. if (((iin != null) && (iin instanceof android.content.IIntentReceiver))) {
  9. return ((android.content.IIntentReceiver) iin);
  10. }
  11. return new android.content.IIntentReceiver.Stub.Proxy(obj);
  12. }
  1. public IInterface queryLocalInterface(String descriptor) {
  2. if (mDescriptor.equals(descriptor)) {
  3. return mOwner;
  4. }
  5. return null;
  6. }

如今是InnerReceiver,详细调用例如以下。返回的是IInterface。这个是在IIntentReceiver.Stub初始化时设置的。

  1. public interface IIntentReceiver extends android.os.IInterface {
  2. /** Local-side IPC implementation stub class. */
  3. public static abstract class Stub extends android.os.Binder implements
  4. android.content.IIntentReceiver {
  5. private static final java.lang.String DESCRIPTOR = "android.content.IIntentReceiver";
  6.  
  7. /** Construct the stub at attach it to the interface. */
  8. public Stub() {
  9. this.attachInterface(this, DESCRIPTOR);
  10. }

如图:第四步

~/Android/frameworks/base/core/java/android/app

----ActivityThread.java

  1. public final class ActivityThread {
  2. ......
  3.  
  4. private final class ApplicationThread extends ApplicationThreadNative {
  5. ......
  6.  
  7. // This function exists to make sure all receiver dispatching is
  8. // correctly ordered, since these are one-way calls and the binder driver
  9. // applies transaction ordering per object for such calls.
  10. public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
  11. int resultCode, String dataStr, Bundle extras, boolean ordered,
  12. boolean sticky) throws RemoteException {
  13. receiver.performReceive(intent, resultCode, dataStr, extras, ordered, sticky);
  14. }
  15.  
  16. ......
  17. }
  18.  
  19. ......
  20.  
  21. }

经过一系列折腾,最后在MainActivity和CounterService所在应用程序主线程运行:

  1. receiver.onReceive(mContext, intent);

运行onRecevice函数:  

  1. public class MainActivity extends Activity implements OnClickListener {
  2. ......
  3.  
  4. private BroadcastReceiver counterActionReceiver = new BroadcastReceiver(){
  5. public void onReceive(Context context, Intent intent) {
  6. int counter = intent.getIntExtra(CounterService.COUNTER_VALUE, 0);
  7. String text = String.valueOf(counter);
  8. counterText.setText(text);
  9.  
  10. Log.i(LOG_TAG, "Receive counter event");
  11. }
  12. }
  13.  
  14. ......
  15.  
  16. }

Android 系统广播机制的更多相关文章

  1. Android系统广播机制存在漏洞,恶意软件可绕过安全机制跟踪用户

    前言 国外研究人员披露了Android漏洞(CVE-2018-9489)的信息.Android系统的内部广播机制会暴露敏感的用户和设备信息,手机上安装的应用可在用户不知情或未经许可的情况下访问获取这些 ...

  2. Android系统广播处理机制

    Android系统中的广播是广泛用于应用程序之间通信的一种手段,它类似于事件处理机制,不同的地方就是广播的处理是系统级别的事件处理过程(一般事件处理是控件级别的).在此过程中仍然是离不开Intent对 ...

  3. Android广播机制的深入学习

    部分内容转载自http://www.cnblogs.com/lwbqqyumidi/p/4168017.html 1.Android广播机制概述 Android广播分为两个方面:广播发送者和广播接收者 ...

  4. Android总结篇系列:Android广播机制

    1.Android广播机制概述 Android广播分为两个方面:广播发送者和广播接收者,通常情况下,BroadcastReceiver指的就是广播接收者(广播接收器).广播作为Android组件间的通 ...

  5. Android广播机制概述

    1.Android广播机制概述 Android广播分为两个方面:广播发送者和广播接收者,通常情况下,BroadcastReceiver指的就是广播接收者(广播接收器).广播作为Android组件间的通 ...

  6. Android广播机制:Broadcast

    转载:Android总结篇系列:Android广播机制 1.Android广播机制概述 Android广播分为两个方面:广播发送者和广播接收者,通常情况下,BroadcastReceiver指的就是广 ...

  7. Android广播机制(转)

    1.Android广播机制概述 Android广播分为两个方面:广播发送者和广播接收者,通常情况下,BroadcastReceiver指的就是广播接收者(广播接收器).广播作为Android组件间的通 ...

  8. Android广播机制

    原文出处: Android总结篇系列:Android广播机制 1.Android广播机制概述 Android广播分为两个方面:广播发送者和广播接收者,通常情况下,BroadcastReceiver指的 ...

  9. Android随笔之——Android广播机制Broadcast详解

    在Android中,有一些操作完成以后,会发送广播,比如说发出一条短信,或打出一个电话,如果某个程序接收了这个广播,就会做相应的处理.这个广播跟我们传统意义中的电台广播有些相似之处.之所以叫做广播,就 ...

随机推荐

  1. JavaScript 基础:Babel 转译 class 过程窥探

    零.前言 虽然在 JavaScript 中对象无处不在,但这门语言并不使用经典的基于类的继承方式,而是依赖原型,至少在 ES6 之前是这样的.当时,假设我们要定义一个可以设置 id 与坐标的类,我们会 ...

  2. java 之Thread线程相关yield()、sleep()、wait()、join()、run和start方法详解

    1.sleep() 使当前线程(即调用该方法的线程)暂停执行一段时间,让其他线程有机会继续执行,但它并不释放对象锁.也就是说如果有synchronized同步快,其他线程仍然不能访问共享数据.注意该方 ...

  3. 解决windows管理员已阻止你运行此应用问题

    按WIN+R键,打开“运行”,然后输入“gpedit.msc",就是打开组策略,这个在控制面板中也可以打开. 在组策略里找到“计算机配置”-“Windows设置”-“安全设置”-“本地策略” ...

  4. PAT Basic 1039

    1039 到底买不买 小红想买些珠子做一串自己喜欢的珠串.卖珠子的摊主有很多串五颜六色的珠串,但是不肯把任何一串拆散了卖.于是小红要你帮忙判断一下,某串珠子里是否包含了全部自己想要的珠子?如果是,那么 ...

  5. Android开发——Activity启动模式详解

    1. Activity的启动模式 本文原创,转载请注明出处:http://blog.csdn.net/seu_calvin/article/details/52054893 1.1 Standard标 ...

  6. Httpclient 和 HtmlUnit 对比

    unit相比于client更接近浏览器,模拟浏览器访问状态,两者都是将网页封装成了一个对象,不同是,client能更好地操作网页元素. but 官方unit已经很老了,08年的,已经不更新了.

  7. localstorage与sessionstorage的使用

    cookie,sessionStorage,localeStorage的区别 cookie是存储在浏览器端,并且随浏览器的请求一起发送到服务器端的,它有一定的过期时间,到了过期时间自动会消失.sess ...

  8. WordPress 编辑器没有可视化

    第一次安装wordpress后出现文章编辑器只有一行按钮的问题,即使我安装了其他的编辑插件也是一样只有一行, 解决方法: 原来是再Users->All Users 中勾选了Disable the ...

  9. SPOJ GSS2 Can you answer these queries II ——线段树

    [题目分析] 线段树,好强! 首先从左往右依次扫描,线段树维护一下f[].f[i]表示从i到当前位置的和的值. 然后询问按照右端点排序,扫到一个位置,就相当于查询区间历史最值. 关于历史最值问题: 标 ...

  10. bzoj 4401 块的计数 思想+模拟+贪心

    块的计数 Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 455  Solved: 261[Submit][Status][Discuss] Descr ...