Android广播之发送广播的源码分析

来源:互联网 发布:女娲 知乎 编辑:程序博客网 时间:2024/06/08 06:01
 

Android广播之发送广播的源码分析

 736人阅读 评论(0) 收藏 举报
 分类:

前面文章介绍了Android注册广播的过程,这篇介绍下广播的发送过程。

广播的发送过程比广播的注册过程复杂的多,主要有以下几个步骤:

1.广播的发送者将一个特定类型的广播发送给ActivityManagerService。

2.AMS接收到这个广播后,首先找到与这个广播对应的广播接收者,然后将它们添加到一个广播调度队列中,再将这个调度队列传递给BroadcastQueue,最后向BroadcastQueue的消息队列发送一个类型为BROADCAST_INTENT_MSG的消息,此时对于广播发送者来说,一个广播的发送就完成了。

3.当消息队列中的BROADCAST_INTENT_MSG消息被处理时,BroadcastQueue就会从广播调度队列中找对需要接收广播的接收者,并且将对应的广播发送给它们所运行在的应用程序进程。

4.广播接收者所运行在的应用程序进程接收到广播后,并不是直接将接收到的广播分发给各个广播接收者来处理,而是将接收到的广播封装成一个消息,并且发送到主线程的消息队列中。当这个消息被处理时,应用程序进程才会将它所描述的广播发送给相应的广播接收者处理。

惯例先看时序图,由于发送广播的过程有点复杂,所以时序图分开画的。sendBroadcast、sendOrderedBroadcast和sendStickyBroadcast方法在调用broadcastIntent方法之前的流程是一样的,这里只画出sendBroadcast方法的时序图:

说明:一个广播是使用一个Intent对象来描述的,而这个Intent对象的action名称就是用来描述它所对应的广播类型。

广播的发送也是从ContextWrapper类开始的:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @Override  
  2. public void sendBroadcast(Intent intent) {  
  3.     mBase.sendBroadcast(intent);  
  4. }  


ContextImpl类的sendBroadcast方法:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @Override  
  2. public void sendBroadcast(Intent intent) {  
  3.     // 如果调用者是系统进程的话打印log  
  4.     warnIfCallingFromSystemProcess();  
  5.     // Intent的MIME数据类型,没有设置则为null  
  6.     String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());  
  7.     try {  
  8.         // 准备离开应用程序进程,进入AMS进程  
  9.         intent.prepareToLeaveProcess();  
  10.         // 调用ActivityManagerProxy类的broadcastIntent方法来实现广播的发送  
  11.         // ActivityManagerProxy是一个Binder对象的远程接口,而这个Binder对象就是ActivityManagerService  
  12.         ActivityManagerNative.getDefault().broadcastIntent(  
  13.                 mMainThread.getApplicationThread(), intent, resolvedType, null,  
  14.                 Activity.RESULT_OK, nullnullnull, AppOpsManager.OP_NONE, nullfalsefalse,  
  15.                 getUserId());  
  16.     } catch (RemoteException e) {  
  17.         throw new RuntimeException("Failure from system", e);  
  18.     }  
  19. }  


ActivityManagerService类的broadcastIntent方法:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public final int broadcastIntent(IApplicationThread caller,  
  2.         Intent intent, String resolvedType, IIntentReceiver resultTo,  
  3.         int resultCode, String resultData, Bundle resultExtras,  
  4.         String[] requiredPermissions, int appOp, Bundle options,  
  5.         boolean serialized, boolean sticky, int userId) {  
  6.     // 执行调用者不是独立进程的判断  
  7.     enforceNotIsolatedCaller("broadcastIntent");  
  8.     synchronized(this) {  
  9.         intent = verifyBroadcastLocked(intent);  
  10.   
  11.         // 通过ApplicationThread对象从成员变量mLruProcesses列表中查找调用者的ProcessRecord对象  
  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.         // 调用broadcastIntentLocked方法处理 intent 所描述的广播  
  17.         int res = broadcastIntentLocked(callerApp,  
  18.                 callerApp != null ? callerApp.info.packageName : null,  
  19.                 intent, resolvedType, resultTo, resultCode, resultData, resultExtras,  
  20.                 requiredPermissions, appOp, null, serialized, sticky,  
  21.                 callingPid, callingUid, userId);  
  22.         Binder.restoreCallingIdentity(origId);  
  23.         return res;  
  24.     }  
  25. }  


再看后续时序图:

broadcastIntentLocked方法中主要是用来查找目标广播接收者的:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * State of all active sticky broadcasts per user.  Keys are the action of the 
  3.  * sticky Intent, values are an ArrayList of all broadcasted intents with 
  4.  * that action (which should usually be one).  The SparseArray is keyed 
  5.  * by the user ID the sticky is for, and can include UserHandle.USER_ALL 
  6.  * for stickies that are sent to all users. 
  7.  */  
  8. final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts =  
  9.         new SparseArray<ArrayMap<String, ArrayList<Intent>>>();  
  10.   
  11. private final int broadcastIntentLocked(ProcessRecord callerApp,  
  12.         String callerPackage, Intent intent, String resolvedType,  
  13.         IIntentReceiver resultTo, int resultCode, String resultData,  
  14.         Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle options,  
  15.         boolean ordered, boolean sticky, int callingPid, int callingUid, int userId) {  
  16.     intent = new Intent(intent);  
  17.   
  18.     // By default broadcasts do not go to stopped apps.  
  19.     // 设置这个flag后,intent将不会去匹配这个package中当前停止运行的组件。  
  20.     intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);  
  21.   
  22.     // If we have not finished booting, don't allow this to launch new processes.  
  23.     // FLAG_RECEIVER_BOOT_UPGRADE标志是广播用于系统升级的,如果设置了该标记,允许系统在启动完成前发送广播  
  24.     if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {  
  25.         // 追加FLAG_RECEIVER_REGISTERED_ONLY标志后,只有动态注册的广播接收者能收到广播  
  26.         // 这是因为在系统启动过程中,PackageManagerService可能还未启动,此时AMS是无法获得静态注册的广播接收者的  
  27.         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);  
  28.     }  
  29.   
  30.     if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,  
  31.             (sticky ? "Broadcast sticky: ""Broadcast: ") + intent  
  32.             + " ordered=" + ordered + " userid=" + userId);  
  33.     if ((resultTo != null) && !ordered) {  
  34.         Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");  
  35.     }  
  36.   
  37.     // 处理调用者uid  
  38.     userId = handleIncomingUser(callingPid, callingUid, userId,  
  39.             true, ALLOW_NON_FULL, "broadcast", callerPackage);  
  40.   
  41.     // Make sure that the user who is receiving this broadcast is running.  
  42.     // If not, we will just skip it. Make an exception for shutdown broadcasts  
  43.     // and upgrade steps.  
  44.   
  45.     if (userId != UserHandle.USER_ALL && !isUserRunningLocked(userId, false)) {  
  46.         if ((callingUid != Process.SYSTEM_UID  
  47.                 || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0)  
  48.                 && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {  
  49.             Slog.w(TAG, "Skipping broadcast of " + intent  
  50.                     + ": user " + userId + " is stopped");  
  51.             return ActivityManager.BROADCAST_FAILED_USER_STOPPED;  
  52.         }  
  53.     }  
  54.   
  55.     BroadcastOptions brOptions = null;  
  56.     if (options != null) {  
  57.         brOptions = new BroadcastOptions(options);  
  58.         if (brOptions.getTemporaryAppWhitelistDuration() > 0) {  
  59.             // See if the caller is allowed to do this.  Note we are checking against  
  60.             // the actual real caller (not whoever provided the operation as say a  
  61.             // PendingIntent), because that who is actually supplied the arguments.  
  62.             if (checkComponentPermission(  
  63.                     android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,  
  64.                     Binder.getCallingPid(), Binder.getCallingUid(), -1true)  
  65.                     != PackageManager.PERMISSION_GRANTED) {  
  66.                 String msg = "Permission Denial: " + intent.getAction()  
  67.                         + " broadcast from " + callerPackage + " (pid=" + callingPid  
  68.                         + ", uid=" + callingUid + ")"  
  69.                         + " requires "  
  70.                         + android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST;  
  71.                 Slog.w(TAG, msg);  
  72.                 throw new SecurityException(msg);  
  73.             }  
  74.         }  
  75.     }  
  76.   
  77.     /* 
  78.      * Prevent non-system code (defined here to be non-persistent 
  79.      * processes) from sending protected broadcasts. 
  80.      * 防止非系统代码(这里定义为非持久性进程)发送受保护的广播 
  81.      */  
  82.     int callingAppId = UserHandle.getAppId(callingUid);  
  83.     if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID  
  84.         || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID  
  85.         || callingAppId == Process.NFC_UID || callingUid == 0) {  
  86.         // Always okay.  
  87.     } else if (callerApp == null || !callerApp.persistent) {// 调用者为null或者调用者不是持久性进程  
  88.         try {  
  89.             // 非系统应用不能发送受保护的广播  
  90.             if (AppGlobals.getPackageManager().isProtectedBroadcast(  
  91.                     intent.getAction())) {  
  92.                 String msg = "Permission Denial: not allowed to send broadcast "  
  93.                         + intent.getAction() + " from pid="  
  94.                         + callingPid + ", uid=" + callingUid;  
  95.                 Slog.w(TAG, msg);  
  96.                 throw new SecurityException(msg);  
  97.             } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(intent.getAction())) {  
  98.                 // Special case for compatibility(兼容性): we don't want apps to send this,  
  99.                 // but historically it has not been protected and apps may be using it  
  100.                 // to poke(干涉) their own app widget.  So, instead of making it protected,  
  101.                 // just limit it to the caller.  
  102.                 if (callerApp == null) {  
  103.                     String msg = "Permission Denial: not allowed to send broadcast "  
  104.                             + intent.getAction() + " from unknown caller.";  
  105.                     Slog.w(TAG, msg);  
  106.                     throw new SecurityException(msg);  
  107.                 // 接收目标组件不为null  
  108.                 } else if (intent.getComponent() != null) {  
  109.                     // They are good enough to send to an explicit component...  verify  
  110.                     // it is being sent to the calling app.  
  111.                     if (!intent.getComponent().getPackageName().equals(  
  112.                             callerApp.info.packageName)) {  
  113.                         String msg = "Permission Denial: not allowed to send broadcast "  
  114.                                 + intent.getAction() + " to "  
  115.                                 + intent.getComponent().getPackageName() + " from "  
  116.                                 + callerApp.info.packageName;  
  117.                         Slog.w(TAG, msg);  
  118.                         throw new SecurityException(msg);  
  119.                     }  
  120.                 } else {  
  121.                     // 发送者不为null,接收者组件为null时,设置接收者只能是发送者  
  122.                     // Limit broadcast to their own package.  
  123.                     intent.setPackage(callerApp.info.packageName);  
  124.                 }  
  125.             }  
  126.         } catch (RemoteException e) {  
  127.             Slog.w(TAG, "Remote exception", e);  
  128.             return ActivityManager.BROADCAST_SUCCESS;  
  129.         }  
  130.     }  
  131.   
  132.     final String action = intent.getAction();  
  133.     if (action != null) {  
  134.         // 特殊的Action有不同的处理方式  
  135.         switch (action) {  
  136.             case Intent.ACTION_UID_REMOVED:  
  137.             case Intent.ACTION_PACKAGE_REMOVED:  
  138.             case Intent.ACTION_PACKAGE_CHANGED:  
  139.             case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:  
  140.             case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:  
  141.                 // Handle special intents: if this broadcast is from the package  
  142.                 // manager about a package being removed, we need to remove all of  
  143.                 // its activities from the history stack.  
  144.                 if (checkComponentPermission(  
  145.                         android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,  
  146.                         callingPid, callingUid, -1true)  
  147.                         != PackageManager.PERMISSION_GRANTED) {  
  148.                     String msg = "Permission Denial: " + intent.getAction()  
  149.                             + " broadcast from " + callerPackage + " (pid=" + callingPid  
  150.                             + ", uid=" + callingUid + ")"  
  151.                             + " requires "  
  152.                             + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;  
  153.                     Slog.w(TAG, msg);  
  154.                     throw new SecurityException(msg);  
  155.                 }  
  156.                 switch (action) {  
  157.                     case Intent.ACTION_UID_REMOVED:  
  158.                         final Bundle intentExtras = intent.getExtras();  
  159.                         final int uid = intentExtras != null  
  160.                                 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;  
  161.                         if (uid >= 0) {  
  162.                             mBatteryStatsService.removeUid(uid);  
  163.                             mAppOpsService.uidRemoved(uid);  
  164.                         }  
  165.                         break;  
  166.                     // app正在移动到SD卡中,发出的广播  
  167.                     case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:  
  168.                         // If resources are unavailable just force stop all those packages  
  169.                         // and flush the attribute cache as well.  
  170.                         String list[] =  
  171.                                 intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);  
  172.                         if (list != null && list.length > 0) {  
  173.                             for (int i = 0; i < list.length; i++) {  
  174.                                 forceStopPackageLocked(list[i], -1falsetruetrue,  
  175.                                         falsefalse, userId, "storage unmount");  
  176.                             }  
  177.                             // 清空app的任务栈  
  178.                             mRecentTasks.cleanupLocked(UserHandle.USER_ALL);  
  179.                             // 发送app不可用的广播  
  180.                             sendPackageBroadcastLocked(  
  181.                                     IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list,  
  182.                                     userId);  
  183.                         }  
  184.                         break;  
  185.                     // app完成移动到SD的操作,发出的广播  
  186.                     case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:  
  187.                         mRecentTasks.cleanupLocked(UserHandle.USER_ALL);  
  188.                         break;  
  189.                     case Intent.ACTION_PACKAGE_REMOVED:  
  190.                     case Intent.ACTION_PACKAGE_CHANGED:  
  191.                         Uri data = intent.getData();  
  192.                         String ssp;  
  193.                         if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {  
  194.                             boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action);  
  195.                             boolean fullUninstall = removed &&  
  196.                                     !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);  
  197.                             final boolean killProcess =  
  198.                                     !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false);  
  199.                             if (killProcess) {  
  200.                                 forceStopPackageLocked(ssp, UserHandle.getAppId(  
  201.                                         intent.getIntExtra(Intent.EXTRA_UID, -1)),  
  202.                                         falsetruetruefalse, fullUninstall, userId,  
  203.                                         removed ? "pkg removed" : "pkg changed");  
  204.                             }  
  205.                             if (removed) {  
  206.                                 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,  
  207.                                         new String[] {ssp}, userId);  
  208.                                 if (fullUninstall) {  
  209.                                     mAppOpsService.packageRemoved(  
  210.                                             intent.getIntExtra(Intent.EXTRA_UID, -1), ssp);  
  211.   
  212.                                     // Remove all permissions granted from/to this package  
  213.                                     removeUriPermissionsForPackageLocked(ssp, userId, true);  
  214.   
  215.                                     removeTasksByPackageNameLocked(ssp, userId);  
  216.                                     mBatteryStatsService.notePackageUninstalled(ssp);  
  217.                                 }  
  218.                             } else {  
  219.                                 cleanupDisabledPackageComponentsLocked(ssp, userId, killProcess,  
  220.                                         intent.getStringArrayExtra(  
  221.                                                 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST));  
  222.                             }  
  223.                         }  
  224.                         break;  
  225.                 }  
  226.                 break;  
  227.             case Intent.ACTION_PACKAGE_ADDED:  
  228.                 // Special case for adding a package: by default turn on compatibility mode.  
  229.                 Uri data = intent.getData();  
  230.                 String ssp;  
  231.                 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {  
  232.                     final boolean replacing =  
  233.                             intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);  
  234.                     mCompatModePackages.handlePackageAddedLocked(ssp, replacing);  
  235.   
  236.                     try {  
  237.                         ApplicationInfo ai = AppGlobals.getPackageManager().  
  238.                                 getApplicationInfo(ssp, 00);  
  239.                         mBatteryStatsService.notePackageInstalled(ssp,  
  240.                                 ai != null ? ai.versionCode : 0);  
  241.                     } catch (RemoteException e) {  
  242.                     }  
  243.                 }  
  244.                 break;  
  245.             case Intent.ACTION_TIMEZONE_CHANGED:  
  246.                 // If this is the time zone changed action, queue up a message that will reset  
  247.                 // the timezone of all currently running processes. This message will get  
  248.                 // queued up before the broadcast happens.  
  249.                 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);  
  250.                 break;  
  251.             case Intent.ACTION_TIME_CHANGED:  
  252.                 // If the user set the time, let all running processes know.  
  253.                 final int is24Hour =  
  254.                         intent.getBooleanExtra(Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, false) ? 1  
  255.                                 : 0;  
  256.                 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_TIME, is24Hour, 0));  
  257.                 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();  
  258.                 synchronized (stats) {  
  259.                     stats.noteCurrentTimeChangedLocked();  
  260.                 }  
  261.                 break;  
  262.             case Intent.ACTION_CLEAR_DNS_CACHE:  
  263.                 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG);  
  264.                 break;  
  265.             case Proxy.PROXY_CHANGE_ACTION:  
  266.                 ProxyInfo proxy = intent.getParcelableExtra(Proxy.EXTRA_PROXY_INFO);  
  267.                 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG, proxy));  
  268.                 break;  
  269.         }  
  270.     }  
  271.     //SmartContainer modified begin  
  272.     if (!SmartContainerConfig.WITH_OUT_VIRTUAL_BOX){  
  273.         if (mAMSFunc.processSpecialIntent(intent,callingUid, userId) != 0)  
  274.             return ActivityManager.BROADCAST_SUCCESS;  
  275.     }  
  276.     //SmartContainer modified end  
  277.   
  278.     // Add to the sticky list if requested.  
  279.     if (sticky) {  
  280.         // 粘性广播要加BROADCAST_STICKY权限  
  281.         if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,  
  282.                 callingPid, callingUid)  
  283.                 != PackageManager.PERMISSION_GRANTED) {  
  284.             String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="  
  285.                     + callingPid + ", uid=" + callingUid  
  286.                     + " requires " + android.Manifest.permission.BROADCAST_STICKY;  
  287.             Slog.w(TAG, msg);  
  288.             throw new SecurityException(msg);  
  289.         }  
  290.         // 发送粘性广播不能有其他权限  
  291.         if (requiredPermissions != null && requiredPermissions.length > 0) {  
  292.             Slog.w(TAG, "Can't broadcast sticky intent " + intent  
  293.                     + " and enforce permissions " + Arrays.toString(requiredPermissions));  
  294.             return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;  
  295.         }  
  296.         // 粘性广播不能发给指定的接收组件  
  297.         if (intent.getComponent() != null) {  
  298.             throw new SecurityException(  
  299.                     "Sticky broadcasts can't target a specific component");  
  300.         }  
  301.         // We use userId directly here, since the "all" target is maintained  
  302.         // as a separate set of sticky broadcasts.  
  303.         if (userId != UserHandle.USER_ALL) {  
  304.             // But first, if this is not a broadcast to all users, then  
  305.             // make sure it doesn't conflict with an existing broadcast to  
  306.             // all users.  
  307.             // 如果广播不是发给所有用户的,则确认对所有用户它不会跟当前存在的广播冲突  
  308.             ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(  
  309.                     UserHandle.USER_ALL);  
  310.             if (stickies != null) {  
  311.                 // 根据Action获取action相同的Intent列表  
  312.                 ArrayList<Intent> list = stickies.get(intent.getAction());  
  313.                 if (list != null) {  
  314.                     int N = list.size();  
  315.                     int i;  
  316.                     for (i=0; i<N; i++) {  
  317.                         // 粘性广播发送后是会保存下来的,故如果已经存在则不需要重新发送  
  318.                         if (intent.filterEquals(list.get(i))) {  
  319.                             throw new IllegalArgumentException(  
  320.                                     "Sticky broadcast " + intent + " for user "  
  321.                                     + userId + " conflicts with existing global broadcast");  
  322.                         }  
  323.                     }  
  324.                 }  
  325.             }  
  326.         }  
  327.         // 在mStickyBroadcasts中根据参数userId查找以Action、广播列表为键值对的stickies,  
  328.         // 如果不存在,则创建并添加  
  329.         ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);  
  330.         if (stickies == null) {  
  331.             stickies = new ArrayMap<>();  
  332.             mStickyBroadcasts.put(userId, stickies);  
  333.         }  
  334.         // 在stickies中查找是否存在与参数intent的Action名称对应的一个粘性广播列表list,  
  335.         // 如果不存在,则创建并添加  
  336.         ArrayList<Intent> list = stickies.get(intent.getAction());  
  337.         if (list == null) {  
  338.             list = new ArrayList<>();  
  339.             stickies.put(intent.getAction(), list);  
  340.         }  
  341.         final int stickiesCount = list.size();  
  342.         int i;  
  343.         // 遍历检查在粘性广播列表list中是否存在一个与参数intent一致的广播  
  344.         for (i = 0; i < stickiesCount; i++) {  
  345.             // 如果存在则用intent参数所描述的广播来替换它  
  346.             if (intent.filterEquals(list.get(i))) {  
  347.                 // This sticky already exists, replace it.  
  348.                 list.set(i, new Intent(intent));  
  349.                 break;  
  350.             }  
  351.         }  
  352.         // 说明list列表中不存在与intent参数一致的广播  
  353.         if (i >= stickiesCount) {  
  354.             // 则把该intent所描述的广播添加到list列表中  
  355.             list.add(new Intent(intent));  
  356.         }  
  357.     }  
  358.   
  359.     int[] users;  
  360.     if (userId == UserHandle.USER_ALL) {  
  361.         // Caller wants broadcast to go to all started users.  
  362.         users = mStartedUserArray;  
  363.     } else {  
  364.         // Caller wants broadcast to go to one specific user.  
  365.         users = new int[] {userId};  
  366.     }  
  367.   
  368.     //SmartContainer Modified begin  
  369.     int alternativeBoxId = userId;  
  370.     Set<Integer> boxesToReceive = new HashSet<Integer>();  
  371.     boxesToReceive.add(userId);  
  372.     //SmartContainer Modified end  
  373.     // Figure out who all will receive this broadcast.  
  374.     List receivers = null;// 静态广播接收器列表  
  375.     List<BroadcastFilter> registeredReceivers = null;// 动态广播接收器列表  
  376.     // Need to resolve the intent to interested receivers...  
  377.     if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)  
  378.              == 0) {  
  379.         // 之前讲解注册广播时,静态注册的广播都保存在PMS中的mReceivers中了,  
  380.         // 现在到PMS中找到所有静态注册的目标广播接收者,并保存在列表receivers中  
  381.         receivers = collectReceiverComponents(intent, resolvedType, callingUid, users);  
  382.     }  
  383.   
  384.     //SmartContainer modified begin  
  385.     if (!SmartContainerConfig.WITH_OUT_VIRTUAL_BOX){  
  386.         if (receivers != null && receivers.size() > 0 && callerPackage!= null){  
  387.             mAMSFunc.processReceiverComponents(boxesToReceive, receivers, callerPackage, userId);  
  388.         }  
  389.     }  
  390.     //SmartContainer modified end  
  391.   
  392.     // 没有指定接收者组件名  
  393.     if (intent.getComponent() == null) {  
  394.         if (userId == UserHandle.USER_ALL && callingUid == Process.SHELL_UID) {  
  395.             // Query one target user at a time, excluding shell-restricted users  
  396.             UserManagerService ums = getUserManagerLocked();  
  397.             for (int i = 0; i < users.length; i++) {  
  398.                 if (ums.hasUserRestriction(  
  399.                         UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) {  
  400.                     continue;  
  401.                 }  
  402.                 List<BroadcastFilter> registeredReceiversForUser =  
  403.                         mReceiverResolver.queryIntent(intent,  
  404.                                 resolvedType, false, users[i]);  
  405.                 if (registeredReceivers == null) {  
  406.                     registeredReceivers = registeredReceiversForUser;  
  407.                 } else if (registeredReceiversForUser != null) {  
  408.                     registeredReceivers.addAll(registeredReceiversForUser);  
  409.                 }  
  410.             }  
  411.         } else {  
  412.             // 之前讲解注册广播时,动态注册的广播都存放在AMS的mReceiverResolver中了,  
  413.             // 这里就在里面找到动态注册的目标广播接收者,并保存在registeredReceivers列表中  
  414.             registeredReceivers = mReceiverResolver.queryIntent(intent,  
  415.                     resolvedType, false, userId);  
  416.             //SmartContainer modified begin  
  417.             if (userId != UserHandle.USER_ALL && !SmartContainerConfig.WITH_OUT_VIRTUAL_BOX &&  
  418.                     (registeredReceivers == null || registeredReceivers.size() == 0)) {  
  419.                 alternativeBoxId = mAMSFunc.processRegisterReceivers(registeredReceivers,  
  420.                         boxesToReceive, intent, resolvedType, userId, alternativeBoxId, callingUid);  
  421.             }  
  422.             //SmartContainer modified end  
  423.         }  
  424.     }  
  425.   
  426.     // 查看intent的flag有没有设置FLAG_RECEIVER_REPLACE_PENDING,如果设置的话,  
  427.     // AMS就会在当前的系统中查看有没有相同的intent还未处理,如果有的话,就用当前这个新的intent  
  428.     // 来替换旧的intent。  
  429.     final boolean replacePending =  
  430.             (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;  
  431.   
  432.     if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueing broadcast: " + intent.getAction()  
  433.             + " replacePending=" + replacePending);  
  434.   
  435.     int NR = registeredReceivers != null ? registeredReceivers.size() : 0;  
  436.     // 参数ordered标记当前发送的广播是否是有序广播,如果不是,并且存在动态注册的目标广播接收者  
  437.     if (!ordered && NR > 0) {  
  438.         // If we are not serializing this broadcast, then send the  
  439.         // registered receivers separately so they don't wait for the  
  440.         // components to be launched.  
  441.         // broadcastQueueForIntent方法判断要发送的广播是前台广播还是后台广播,如果是前台广播则返回前台广播队列,  
  442.         // 不同队列处理超时的时间不一样:前台10秒、后台60秒  
  443.         final BroadcastQueue queue = broadcastQueueForIntent(intent);  
  444.         //SmartContainer modified begin  
  445.         if( SmartContainerConfig.WITH_OUT_APP_CLONE || boxesToReceive.size() == 1  
  446.                 || userId == UserHandle.USER_ALL ){  
  447.             // 将intent所描述的广播,以及动态注册的目标广播接收者封装成一个BroadcastRecord对象r,  
  448.             // 用来描述AMS要执行的一个广播转发任务  
  449.             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,  
  450.                     callerPackage, callingPid, callingUid, resolvedType, requiredPermissions,  
  451.                     appOp, brOptions, registeredReceivers, resultTo, resultCode, resultData,  
  452.                     resultExtras, ordered, sticky, false, alternativeBoxId);  
  453.             Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r + " intent " + intent);  
  454.             // replaceParallelBroadcastLocked方法根据r到queue中的无序调度队列中查找是否存在与intent描述一致的广播,存在则替换并返回true  
  455.             final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);  
  456.             // 如果replaced为true,说明不需要在无序广播调度队列中增加新的广播转发任务  
  457.             if (!replaced) {  
  458.                 // 否者就把r所描述的广播转发任务放在BroadcastQueue类中的mParallelBroadcasts无序调度队列中  
  459.                 queue.enqueueParallelBroadcastLocked(r);  
  460.                 // 重新调度这个队列中的广播转发任务,从这里可以看出动态注册的广播接收者  
  461.                 // 比静态注册的广播接收者优先接收到无序广播  
  462.                 queue.scheduleBroadcastsLocked();  
  463.             }  
  464.         } else {  
  465.             List<BroadcastFilter> broadcastFilterList = new ArrayList<BroadcastFilter>();  
  466.             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,  
  467.                     callerPackage, callingPid, callingUid, resolvedType, requiredPermissions,  
  468.                     appOp, brOptions, broadcastFilterList, resultTo, resultCode, resultData,  
  469.                     resultExtras, ordered, sticky, false, -1);  
  470.             mAMSFunc.queueNOrderedRegisteredBroadcastForClone(registeredReceivers, r, boxesToReceive, intent, replacePending);  
  471.         }  
  472.   
  473.         //SmartContainer modified end  
  474.         // 到这里,对于无序广播来说,AMS就相当于已经将参数intent描述的广播发给那些动态注册的目标广播接收者了。  
  475.         // 故,这里就将列表registeredReceivers设置为null,将标记动态注册的目标广播接收者个数的变量NR设置为0  
  476.         registeredReceivers = null;  
  477.         NR = 0;  
  478.     }  
  479.   
  480.     // 执行到这里,无论AMS当前接收到的是一个无序广播还是有序广播,都会将该广播及其目标广播接收者封装成一个广播转发任务,  
  481.     // 并添加到一个有序广播调度队列中。但对于无序广播来说,当它们被真正转发时,并不会按照有序广播来转发。  
  482.   
  483.     // Merge into one list.  
  484.     int ir = 0;  
  485.     if (receivers != null) {  
  486.         // A special case for PACKAGE_ADDED: do not allow the package  
  487.         // being added to see this broadcast.  This prevents them from  
  488.         // using this as a back door to get run as soon as they are  
  489.         // installed.  Maybe in the future we want to have a special install  
  490.         // broadcast or such for apps, but we'd like to deliberately make  
  491.         // this decision.  
  492.         String skipPackages[] = null;  
  493.         if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())  
  494.                 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())  
  495.                 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {  
  496.             Uri data = intent.getData();  
  497.             if (data != null) {  
  498.                 // 特殊广播查看ssp有没有指定包名,有则赋值给skipPackages  
  499.                 String pkgName = data.getSchemeSpecificPart();  
  500.                 if (pkgName != null) {  
  501.                     skipPackages = new String[] { pkgName };  
  502.                 }  
  503.             }  
  504.         } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {  
  505.             skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);  
  506.         }  
  507.         if (skipPackages != null && (skipPackages.length > 0)) {  
  508.             for (String skipPackage : skipPackages) {  
  509.                 if (skipPackage != null) {  
  510.                     int NT = receivers.size();  
  511.                     for (int it=0; it<NT; it++) {  
  512.                         ResolveInfo curt = (ResolveInfo)receivers.get(it);  
  513.                         // 如果静态注册的广播接收者应用的包名和skipPackage一致,则从receivers移除  
  514.                         if (curt.activityInfo.packageName.equals(skipPackage)) {  
  515.                             receivers.remove(it);  
  516.                             it--;  
  517.                             NT--;  
  518.                         }  
  519.                     }  
  520.                 }  
  521.             }  
  522.         }  
  523.   
  524.         int NT = receivers != null ? receivers.size() : 0;  
  525.         int it = 0;  
  526.         ResolveInfo curt = null;  
  527.         BroadcastFilter curr = null;  
  528.         // 这里动态注册广播合并的是有序的,因为无序动态广播处理中NR最后被赋值为0了  
  529.         while (it < NT && ir < NR) {  
  530.             if (curt == null) {  
  531.                 // 静态注册的广播是ResolveInfo类型  
  532.                 curt = (ResolveInfo)receivers.get(it);  
  533.             }  
  534.             if (curr == null) {  
  535.                 // 动态注册的广播是BroadcastFilter类型,后面会根据类型判断广播是动态注册还是静态注册的  
  536.                 curr = registeredReceivers.get(ir);  
  537.             }  
  538.             // 如果动态注册广播接收者优先级高于等于静态广播接收者,则把动态注册的广播接收者插入到当前位置,  
  539.             // 静态注册的广播接收者后移,这说明同优先级动态注册的先于静态注册的接收到广播  
  540.             if (curr.getPriority() >= curt.priority) {  
  541.                 // Insert this broadcast record into the final list.  
  542.                 receivers.add(it, curr);  
  543.                 ir++;  
  544.                 curr = null;  
  545.                 it++;  
  546.                 NT++;  
  547.             } else {  
  548.                 // Skip to the next ResolveInfo in the final list.  
  549.                 it++;  
  550.                 curt = null;  
  551.             }  
  552.         }  
  553.     }  
  554.     // 把优先级低于所有静态注册广播接收者的动态广播接收者都追加到receivers列表中的末尾  
  555.     while (ir < NR) {  
  556.         if (receivers == null) {  
  557.             receivers = new ArrayList();  
  558.         }  
  559.         receivers.add(registeredReceivers.get(ir));  
  560.         ir++;  
  561.     }  
  562.     // 到这里,对于无序广播来说,静态注册的目标广播接收者就全部保存在列表receivers中了;  
  563.     // 而对于有序广播来说,静态注册和动态注册的目标广播接收者也全部保存在列表receivers中了。  
  564.   
  565.     if ((receivers != null && receivers.size() > 0)  
  566.             || resultTo != null) {  
  567.         //SmartContainer Modified begin  
  568.         if ( SmartContainerConfig.WITH_OUT_VIRTUAL_BOX || userId == UserHandle.USER_ALL  
  569.                 || receivers == null || receivers.size() == 0) {  
  570.             BroadcastQueue queue = broadcastQueueForIntent(intent);  
  571.             // 将intent所描述的广播,以及剩余的其他目标广播接收者封装成另外一个BroadcastRecord对象r,  
  572.             // 用来描述AMS要执行的另一个广播转发任务,并且添加到有序广播调度队列中。  
  573.             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,  
  574.                     callerPackage, callingPid, callingUid, resolvedType,  
  575.                     requiredPermissions, appOp, brOptions, receivers, resultTo, resultCode,  
  576.                     resultData, resultExtras, ordered, sticky, false, userId);  
  577.   
  578.             Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r  
  579.                     + ": prev had " + queue.mOrderedBroadcasts.size());  
  580.             Slog.i(TAG_BROADCAST,  
  581.                     "Enqueueing broadcast " + r.intent.getAction());  
  582.   
  583.             // replaceOrderedBroadcastLocked方法根据r到queue中的有序调度队列中查找是否存在与intent描述一致的广播,存在则替换并返回true  
  584.             boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);  
  585.             // 如果replaced为true,说明不需要在有序广播调度队列中增加新的广播转发任务  
  586.             if (!replaced) {  
  587.                 // 否者把r所描述的广播转发任务放在BroadcastQueue类中的mOrderedBroadcasts有序广播调度队列中  
  588.                 queue.enqueueOrderedBroadcastLocked(r);  
  589.                 // 重新调度这个队列中的广播转发任务  
  590.                 queue.scheduleBroadcastsLocked();  
  591.             }  
  592.         } else {  
  593.             List receiverList = new ArrayList();  
  594.             BroadcastQueue queue = broadcastQueueForIntent(intent);  
  595.             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,  
  596.                     callerPackage, callingPid, callingUid, resolvedType,  
  597.                     requiredPermissions, appOp, brOptions, receiverList, resultTo, resultCode,  
  598.                     resultData, resultExtras, ordered, sticky, false, -1);  
  599.             mAMSFunc.queueFinalBroadcastForClone(receivers, r, boxesToReceive, intent, userId, replacePending);  
  600.         }  
  601.         //SmartContainer Modified end  
  602.     }  
  603.   
  604.     return ActivityManager.BROADCAST_SUCCESS;  
  605. }  


至此,AMS就找到参数intent所描述广播的目标广播接收者了,并且分别将它们保存在了BroadcastRecord类的无序广播调度队列mParallelBroadcasts(包括动态注册的无序广播接收者)中和有序广播调度队列mOrderedBroadcasts(包括动态注册的有序广播接收者和所有静态注册的广播接收者)中。

接下来,AMS就会调用BroadcastQueue类中的scheduleBroadcastsLocked方法将intent所描述的广播转发给目标广播接收者处理:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public void scheduleBroadcastsLocked() {  
  2.     if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["  
  3.             + mQueueName + "]: current="  
  4.             + mBroadcastsScheduled);  
  5.   
  6.     if (mBroadcastsScheduled) {  
  7.         return;  
  8.     }  
  9.     mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));  
  10.     mBroadcastsScheduled = true;  
  11. }  


上面mBroadcastsScheduled参数是用来标记是否已经向消息队列发送了一个类型为BROADCAST_INTENT_MSG消息。BroadcastQueue就是通过这个消息来调度保存在无序广播调度队列和有序广播调度队列中的广播转发任务的。

这里,虽然还没有将广播转发给各目标广播接收者,但是当它执行完成这一步之后,广播发送者就会认为这个广播已经发送成功了。从这里就可以看出,广播的发送和接收是异步的。

mHandler是BroadcastQueue类的内部类BroadcastHandler的实例,在BroadcastQueue类的构造方法中赋初值。

下面看下它的handleMessage方法:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. final BroadcastHandler mHandler;  
  2.   
  3. private final class BroadcastHandler extends Handler {  
  4.     public BroadcastHandler(Looper looper) {  
  5.         super(looper, nulltrue);  
  6.     }  
  7.   
  8.     @Override  
  9.     public void handleMessage(Message msg) {  
  10.         switch (msg.what) {  
  11.             case BROADCAST_INTENT_MSG: {  
  12.                 if (DEBUG_BROADCAST) Slog.v(  
  13.                         TAG_BROADCAST, "Received BROADCAST_INTENT_MSG");  
  14.                 // 处理广播的转发任务  
  15.                 processNextBroadcast(true);  
  16.             } break;  
  17.             case BROADCAST_TIMEOUT_MSG: {  
  18.                 synchronized (mService) {  
  19.                     // 处理广播超时的操作,报ANR异常  
  20.                     broadcastTimeoutLocked(true);  
  21.                 }  
  22.             } break;  
  23.             case SCHEDULE_TEMP_WHITELIST_MSG: {  
  24.                 DeviceIdleController.LocalService dic = mService.mLocalDeviceIdleController;  
  25.                 if (dic != null) {  
  26.                     dic.addPowerSaveTempWhitelistAppDirect(UserHandle.getAppId(msg.arg1),  
  27.                             msg.arg2, true, (String)msg.obj);  
  28.                 }  
  29.             } break;  
  30.         }  
  31.     }  
  32. };  


processNextBroadcast方法主要是用来将广播转发给各目标广播接收者处理:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. final void processNextBroadcast(boolean fromMsg) {  
  2.     /*可以在这里获取允许自启动的名单*/  
  3.   
  4.     synchronized(mService) {  
  5.         BroadcastRecord r;  
  6.   
  7.         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["  
  8.                 + mQueueName + "]: "  
  9.                 + mParallelBroadcasts.size() + " broadcasts, "  
  10.                 + mOrderedBroadcasts.size() + " ordered broadcasts");  
  11.   
  12.         mService.updateCpuStats();  
  13.   
  14.         // fromMsg字段标记是否是从handleMessage中调用的该方法  
  15.         if (fromMsg) {  
  16.             // 设置该参数为false,表示前面发送到消息队列中的BROADCAST_INTENT_MSG消息已经被处理了  
  17.             mBroadcastsScheduled = false;  
  18.         }  
  19.   
  20.         // First, deliver any non-serialized broadcasts right away.  
  21.         // 循环处理保存在无序广播调度队列mParallelBroadcasts中的广播转发任务,  
  22.         // 即:将保存在无序广播调度队列中的广播发送给它的目标广播接收者(动态无序)处理  
  23.         while (mParallelBroadcasts.size() > 0) {  
  24.             // 得到mParallelBroadcasts中保存的第一个广播转发任务r  
  25.             r = mParallelBroadcasts.remove(0);  
  26.             r.dispatchTime = SystemClock.uptimeMillis();  
  27.             r.dispatchClockTime = System.currentTimeMillis();  
  28.             final int N = r.receivers.size();  
  29.             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["  
  30.                     + mQueueName + "] " + r);  
  31.             for (int i=0; i<N; i++) {  
  32.                 Object target = r.receivers.get(i);  
  33.                 if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,  
  34.                         "Delivering non-ordered on [" + mQueueName + "] to registered "  
  35.                         + target + ": " + r);  
  36.                 // 遍历循环将无序广播发送给每一个目标广播接收者(动态注册的)  
  37.                 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);  
  38.             }  
  39.             // 添加r到历史队列中  
  40.             addBroadcastToHistoryLocked(r);  
  41.             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["  
  42.                     + mQueueName + "] " + r);  
  43.         }  
  44.   
  45.         // Now take care of the next serialized one...  
  46.         // 接下来,继续处理保存在有序广播调度队列mOrderedBroadcasts中的广播转发任务。  
  47.   
  48.         // 前面讲到有序广播调度队列mOrderedBroadcasts中描述的广播的目标接收者有可能是静态注册的,  
  49.         // 而这些静态注册的目标广播接收者可能还没有被启动起来,因此,将一个广播发送给它们处理时,先要  
  50.         // 将它们启动起来。事实上,只需要将它们所运行在的应用程序进程启动起来就可以了,因为当这些应用程序  
  51.         // 进程接收到广播时,就会主动将目标广播接收者启动起来。  
  52.   
  53.         // If we are waiting for a process to come up to handle the next  
  54.         // broadcast, then do nothing at this point.  Just in case, we  
  55.         // check that the process we're waiting for still exists.  
  56.         // 该参数是用来描述一个正在等待静态注册的目标广播接收者启动起来的广播转发任务的  
  57.         if (mPendingBroadcast != null) {  
  58.             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,  
  59.                     "processNextBroadcast [" + mQueueName + "]: waiting for "  
  60.                     + mPendingBroadcast.curApp);  
  61.   
  62.             boolean isDead;  
  63.             // 检查这个静态注册的目标广播接收者所运行在的应用程序进程是否已经启动起来  
  64.             synchronized (mService.mPidsSelfLocked) {  
  65.                 ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);  
  66.                 isDead = proc == null || proc.crashing;  
  67.             }  
  68.             // 如果这个应用程序进程没有死亡,就会继续等待  
  69.             if (!isDead) {  
  70.                 // It's still alive, so keep waiting  
  71.                 return;  
  72.             } else {  
  73.                 Slog.w(TAG, "pending app  ["  
  74.                         + mQueueName + "]" + mPendingBroadcast.curApp  
  75.                         + " died before responding to broadcast");  
  76.                 mPendingBroadcast.state = BroadcastRecord.IDLE;  
  77.                 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;  
  78.                 mPendingBroadcast = null;  
  79.             }  
  80.         }  
  81.   
  82.         boolean looped = false;  
  83.           
  84.         // 循环在有序广播调度队列mOrderedBroadcasts(动态有序、所有静态)中找到下一个需要处理的广播转发任务  
  85.         do {  
  86.             // 判断有序广播调度队列中的广播转发任务是否已经处理完了  
  87.             if (mOrderedBroadcasts.size() == 0) {  
  88.                 // No more broadcasts pending, so all done!  
  89.                 mService.scheduleAppGcsLocked();  
  90.                 if (looped) {  
  91.                     // If we had finished the last ordered broadcast, then  
  92.                     // make sure all processes have correct oom and sched  
  93.                     // adjustments.  
  94.                     mService.updateOomAdjLocked();  
  95.                 }  
  96.                 return;  
  97.             }  
  98.             // 取出第一个广播转发任务r  
  99.             r = mOrderedBroadcasts.get(0);  
  100.   
  101.             /* 这里可以统计广播转发任务r中是否包含操作widget的Action:ACTION_APPWIDGET_ENABLED和 
  102.              * ACTION_APPWIDGET_DISABLED的包名r.targetComp.getPackageName()和 
  103.              * 类名r.targetComp.getClassName()以便于后面增加控制自启动的过滤操作*/  
  104.   
  105.             boolean forceReceive = false;  
  106.   
  107.             // Ensure that even if something goes awry(出现差错) with the timeout  
  108.             // detection(超时检测), we catch "hung" broadcasts here, discard(丢弃) them,  
  109.             // and continue to make progress.  
  110.             //  
  111.             // This is only done if the system is ready so that PRE_BOOT_COMPLETED  
  112.             // receivers don't get executed with timeouts. They're intended for  
  113.             // one time heavy lifting after system upgrades and can take  
  114.             // significant amounts of time.  
  115.             // 获取到r所描述的广播转发任务的目标广播接收者的个数  
  116.             int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;  
  117.             // 检查前一个目标广播接收者是否在规定时间内处理完广播  
  118.             if (mService.mProcessesReady && r.dispatchTime > 0) {  
  119.                 long now = SystemClock.uptimeMillis();  
  120.                 if ((numReceivers > 0) &&  
  121.                         (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {  
  122.                     Slog.w(TAG, "Hung broadcast ["  
  123.                             + mQueueName + "] discarded after timeout failure:"  
  124.                             + " now=" + now  
  125.                             + " dispatchTime=" + r.dispatchTime  
  126.                             + " startTime=" + r.receiverTime  
  127.                             + " intent=" + r.intent  
  128.                             + " numReceivers=" + numReceivers  
  129.                             + " nextReceiver=" + r.nextReceiver  
  130.                             + " state=" + r.state);  
  131.                     // 如果目标广播接收者不能按时处理完广播,就强制结束这个广播转发任务  
  132.                     broadcastTimeoutLocked(false); // forcibly(强制) finish this broadcast  
  133.                     // 下面两个参数的设置表示要继续处理有序广播调度队列中的下一个广播转发任务  
  134.                     forceReceive = true;  
  135.                     r.state = BroadcastRecord.IDLE;  
  136.                 }  
  137.             }  
  138.   
  139.             // 检查r所描述的广播转发任务是否正在处理中,即:正在将一个有序广播转发给它的前一个目标广播接收者处理  
  140.             if (r.state != BroadcastRecord.IDLE) {  
  141.                 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,  
  142.                         "processNextBroadcast("  
  143.                         + mQueueName + ") called when not idle (state="  
  144.                         + r.state + ")");  
  145.                 // 如果正在将r所描述的广播转发给它的前一个目标接收者处理,则需要等待这个目标广播接收者处理完  
  146.                 // 该有序广播,然后再转发给下一个目标接收者处理。故这里直接返回  
  147.                 return;  
  148.             }  
  149.   
  150.             // 检查r所描述的广播转发任务是否已经处理完成或者已经被强制结束了  
  151.             if (r.receivers == null || r.nextReceiver >= numReceivers  
  152.                     || r.resultAbort || forceReceive) {  
  153.                 // No more receivers for this broadcast!  Send the final  
  154.                 // result if requested...  
  155.                 if (r.resultTo != null) {  
  156.                     try {  
  157.                         if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,  
  158.                                 "Finishing broadcast [" + mQueueName + "] "  
  159.                                 + r.intent.getAction() + " app=" + r.callerApp);  
  160.                         // 执行广播的发送操作  
  161.                         performReceiveLocked(r.callerApp, r.resultTo,  
  162.                             new Intent(r.intent), r.resultCode,  
  163.                             r.resultData, r.resultExtras, falsefalse, r.userId);  
  164.                         // Set this to null so that the reference  
  165.                         // (local and remote) isn't kept in the mBroadcastHistory.  
  166.                         r.resultTo = null;  
  167.                     } catch (RemoteException e) {  
  168.                         r.resultTo = null;  
  169.                         Slog.w(TAG, "Failure ["  
  170.                                 + mQueueName + "] sending broadcast result of "  
  171.                                 + r.intent, e);  
  172.                     }  
  173.                 }  
  174.   
  175.                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");  
  176.                 // remove掉前面给mHandler发送的BROADCAST_TIMEOUT_MSG消息,  
  177.                 // 表示r所描述的广播转发任务已经在规定时间内处理完了  
  178.                 cancelBroadcastTimeoutLocked();  
  179.   
  180.                 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,  
  181.                         "Finished with ordered broadcast " + r);  
  182.   
  183.                 // ... and on to the next...  
  184.                 addBroadcastToHistoryLocked(r);  
  185.                 // 将r所描述的广播转发任务从有序广播队列中删除  
  186.                 mOrderedBroadcasts.remove(0);  
  187.                 // 这里将r设为null以便继续执行while循环来找到下一个需要处理的广播转发任务  
  188.                 r = null;  
  189.                 looped = true;  
  190.                 continue;  
  191.             }  
  192.         } while (r == null);  
  193.         // 上面循环执行完后,下一个需要处理的广播转发任务就保存在r中了  
  194.   
  195.         // r所描述的广播转发任务的目标广播接收者保存在它的成员变量receivers列表中,  
  196.         // 而下一个目标广播接收者就保存在它的成员变量nextReceiver中,这里得到的是  
  197.         // r所描述的广播转发任务的下一个目标广播接收者在其目标广播接收者列表中的位置  
  198.         // Get the next receiver...  
  199.         int recIdx = r.nextReceiver++;  
  200.   
  201.         // Keep track of when this receiver started, and make sure there  
  202.         // is a timeout message pending to kill it if need be.  
  203.         r.receiverTime = SystemClock.uptimeMillis();  
  204.         // 如果recIdx为0说明广播转发任务刚开始被处理  
  205.         if (recIdx == 0) {  
  206.             // 广播刚被处理,保存当前时间到r.dispatchTime变量中  
  207.             r.dispatchTime = r.receiverTime;  
  208.             r.dispatchClockTime = System.currentTimeMillis();  
  209.             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["  
  210.                     + mQueueName + "] " + r);  
  211.         }  
  212.         // 检查是否已经向消息队列发送了BROADCAST_TIMEOUT_MSG消息  
  213.         if (! mPendingBroadcastTimeoutMessage) {  
  214.             long timeoutTime = r.receiverTime + mTimeoutPeriod;  
  215.             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,  
  216.                     "Submitting BROADCAST_TIMEOUT_MSG ["  
  217.                     + mQueueName + "] for " + r + " at " + timeoutTime);  
  218.             // 如果还没有发送,则向消息队列发送该消息,并且指定它在timeoutTime时间后处理  
  219.             setBroadcastTimeoutLocked(timeoutTime);  
  220.         }  
  221.   
  222.         final BroadcastOptions brOptions = r.options;  
  223.         // 取出r所描述的广播转发任务的下一个目标广播接收者  
  224.         final Object nextReceiver = r.receivers.get(recIdx);  
  225.   
  226.         // 前面说过动态注册广播接收者是BroadcastFilter类型的,这里处理动态有序广播接收者  
  227.         if (nextReceiver instanceof BroadcastFilter) {  
  228.             // Simple case: this is a registered receiver who gets  
  229.             // a direct call.  
  230.             BroadcastFilter filter = (BroadcastFilter)nextReceiver;  
  231.             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,  
  232.                     "Delivering ordered ["  
  233.                     + mQueueName + "] to registered "  
  234.                     + filter + ": " + r);  
  235.             // 这里直接向动态注册的广播接收者发送广播,因为动态注册的广播接收者肯定是已经启动起来的  
  236.             deliverToRegisteredReceiverLocked(r, filter, r.ordered);  
  237.             // 判断r所描述的广播转发任务是否是用来转发无序广播的  
  238.             if (r.receiver == null || !r.ordered) {  
  239.                 // The receiver has already finished, so schedule to  
  240.                 // process the next one.  
  241.                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["  
  242.                         + mQueueName + "]: ordered="  
  243.                         + r.ordered + " receiver=" + r.receiver);  
  244.                 // 如果是则将 r.state设置为IDLE,表示不需要等待它的前一个目标广播接收者处理完成一个广播,  
  245.                 // 就可以将该广播继续发送给它的下一个目标广播接收者处理  
  246.                 r.state = BroadcastRecord.IDLE;  
  247.                 // 为了将广播继续发送给r所描述的广播转发任务的下一个目标广播接收者处理,  
  248.                 // 方法中实现发送BROADCAST_INTENT_MSG消息给消息队列以便继续处理  
  249.                 scheduleBroadcastsLocked();  
  250.             } else {  
  251.                 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {  
  252.                     scheduleTempWhitelistLocked(filter.owningUid,  
  253.                             brOptions.getTemporaryAppWhitelistDuration(), r);  
  254.                 }  
  255.             }  
  256.             return;  
  257.         }  
  258.   
  259.         // 如果r所描述的广播转发任务的下一个目标广播接收者不是BroadcastFilter类型的,那就说明这  
  260.         // 是一个静态注册的广播接收者,这种情况略复杂,因为静态注册的广播接收者可能还没有被启动起来  
  261.         // Hard case: need to instantiate the receiver, possibly  
  262.         // starting its application process to host it.  
  263.   
  264.         // 前面说过,静态注册的广播接收者是ResolveInfo类型的,这里直接强转  
  265.         ResolveInfo info =  
  266.             (ResolveInfo)nextReceiver;  
  267.         ComponentName component = new ComponentName(  
  268.                 info.activityInfo.applicationInfo.packageName,  
  269.                 info.activityInfo.name);  
  270.   
  271.         // 下面主要是根据是否得到权限来决定是否跳过本次广播的发送  
  272.         boolean skip = false;  
  273.         // 根据目标广播接收者所需要的权限检查发送者的Pid和Uid是否符合要求  
  274.         int perm = mService.checkComponentPermission(info.activityInfo.permission,  
  275.                 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,  
  276.                 info.activityInfo.exported);  
  277.         // 如果发送者不符合要求,则直接跳过本次转发  
  278.         if (perm != PackageManager.PERMISSION_GRANTED) {  
  279.             if (!info.activityInfo.exported) {  
  280.                 Slog.w(TAG, "Permission Denial: broadcasting "  
  281.                         + r.intent.toString()  
  282.                         + " from " + r.callerPackage + " (pid=" + r.callingPid  
  283.                         + ", uid=" + r.callingUid + ")"  
  284.                         + " is not exported from uid " + info.activityInfo.applicationInfo.uid  
  285.                         + " due to receiver " + component.flattenToShortString());  
  286.             } else {  
  287.                 Slog.w(TAG, "Permission Denial: broadcasting "  
  288.                         + r.intent.toString()  
  289.                         + " from " + r.callerPackage + " (pid=" + r.callingPid  
  290.                         + ", uid=" + r.callingUid + ")"  
  291.                         + " requires " + info.activityInfo.permission  
  292.                         + " due to receiver " + component.flattenToShortString());  
  293.             }  
  294.             skip = true;  
  295.         // 如果发送者符合要求,就检查发送者申请的权限是否被用户拒绝,拒绝的话也直接跳过本次转发  
  296.         } else if (info.activityInfo.permission != null) {  
  297.             final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);  
  298.             if (opCode != AppOpsManager.OP_NONE  
  299.                     && mService.mAppOpsService.noteOperation(opCode, r.callingUid,  
  300.                             r.callerPackage) != AppOpsManager.MODE_ALLOWED) {  
  301.                 Slog.w(TAG, "Appop Denial: broadcasting "  
  302.                         + r.intent.toString()  
  303.                         + " from " + r.callerPackage + " (pid="  
  304.                         + r.callingPid + ", uid=" + r.callingUid + ")"  
  305.                         + " requires appop " + AppOpsManager.permissionToOp(  
  306.                                 info.activityInfo.permission)  
  307.                         + " due to registered receiver "  
  308.                         + component.flattenToShortString());  
  309.                 skip = true;  
  310.             }  
  311.         }  
  312.   
  313.         /*可以添加关联唤醒的判断逻辑:如根据目标广播接收者的包名/类名前缀判断是否属于第三方push平台,如果是则设置skip为true*/  
  314.   
  315.         // 检查接收者权限  
  316.         if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&  
  317.             r.requiredPermissions != null && r.requiredPermissions.length > 0) {  
  318.             // 循环根据发送者所需的权限检查所有的目标广播接收者的Pid和Uid是否符合要求,一项不符合就直接跳过  
  319.             // 符合要求,就检查接收者申请的权限是否被用户拒绝,拒绝的话也直接跳过  
  320.             for (int i = 0; i < r.requiredPermissions.length; i++) {  
  321.                 String requiredPermission = r.requiredPermissions[i];  
  322.                 try {  
  323.                     perm = AppGlobals.getPackageManager().  
  324.                             checkPermission(requiredPermission,  
  325.                                     info.activityInfo.applicationInfo.packageName,  
  326.                                     UserHandle  
  327.                                             .getUserId(info.activityInfo.applicationInfo.uid));  
  328.                 } catch (RemoteException e) {  
  329.                     perm = PackageManager.PERMISSION_DENIED;  
  330.                 }  
  331.                 if (perm != PackageManager.PERMISSION_GRANTED) {  
  332.                     Slog.w(TAG, "Permission Denial: receiving "  
  333.                             + r.intent + " to "  
  334.                             + component.flattenToShortString()  
  335.                             + " requires " + requiredPermission  
  336.                             + " due to sender " + r.callerPackage  
  337.                             + " (uid " + r.callingUid + ")");  
  338.                     skip = true;  
  339.                     break;  
  340.                 }  
  341.                 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);  
  342.                 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp  
  343.                         && mService.mAppOpsService.noteOperation(appOp,  
  344.                         info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)  
  345.                         != AppOpsManager.MODE_ALLOWED) {  
  346.                     Slog.w(TAG, "Appop Denial: receiving "  
  347.                             + r.intent + " to "  
  348.                             + component.flattenToShortString()  
  349.                             + " requires appop " + AppOpsManager.permissionToOp(  
  350.                             requiredPermission)  
  351.                             + " due to sender " + r.callerPackage  
  352.                             + " (uid " + r.callingUid + ")");  
  353.                     skip = true;  
  354.                     break;  
  355.                 }  
  356.             }  
  357.         }  
  358.         if (!skip && r.appOp != AppOpsManager.OP_NONE  
  359.                 && mService.mAppOpsService.noteOperation(r.appOp,  
  360.                 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)  
  361.                 != AppOpsManager.MODE_ALLOWED) {  
  362.             Slog.w(TAG, "Appop Denial: receiving "  
  363.                     + r.intent + " to "  
  364.                     + component.flattenToShortString()  
  365.                     + " requires appop " + AppOpsManager.opToName(r.appOp)  
  366.                     + " due to sender " + r.callerPackage  
  367.                     + " (uid " + r.callingUid + ")");  
  368.             skip = true;  
  369.         }  
  370.         if (!skip) {  
  371.             skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,  
  372.                     r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);  
  373.         }  
  374.         boolean isSingleton = false;  
  375.         try {  
  376.             isSingleton = mService.isSingleton(info.activityInfo.processName,  
  377.                     info.activityInfo.applicationInfo,  
  378.                     info.activityInfo.name, info.activityInfo.flags);  
  379.         } catch (SecurityException e) {  
  380.             Slog.w(TAG, e.getMessage());  
  381.             skip = true;  
  382.         }  
  383.         if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {  
  384.             if (ActivityManager.checkUidPermission(  
  385.                     android.Manifest.permission.INTERACT_ACROSS_USERS,  
  386.                     info.activityInfo.applicationInfo.uid)  
  387.                             != PackageManager.PERMISSION_GRANTED) {  
  388.                 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()  
  389.                         + " requests FLAG_SINGLE_USER, but app does not hold "  
  390.                         + android.Manifest.permission.INTERACT_ACROSS_USERS);  
  391.                 skip = true;  
  392.             }  
  393.         }  
  394.         if (r.curApp != null && r.curApp.crashing) {  
  395.             // If the target process is crashing, just skip it.  
  396.             Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r  
  397.                     + " to " + r.curApp + ": process crashing");  
  398.             skip = true;  
  399.         }  
  400.         if (!skip) {  
  401.             boolean isAvailable = false;  
  402.             try {  
  403.                 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(  
  404.                         info.activityInfo.packageName,  
  405.                         UserHandle.getUserId(info.activityInfo.applicationInfo.uid));  
  406.             } catch (Exception e) {  
  407.                 // all such failures mean we skip this receiver  
  408.                 Slog.w(TAG, "Exception getting recipient info for "  
  409.                         + info.activityInfo.packageName, e);  
  410.             }  
  411.             if (!isAvailable) {  
  412.                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,  
  413.                         "Skipping delivery to " + info.activityInfo.packageName + " / "  
  414.                         + info.activityInfo.applicationInfo.uid  
  415.                         + " : package no longer available");  
  416.                 skip = true;  
  417.             }  
  418.         }  
  419.   
  420.         if (skip) {  
  421.             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,  
  422.                     "Skipping delivery of ordered [" + mQueueName + "] "  
  423.                     + r + " for whatever reason");  
  424.             r.receiver = null;  
  425.             r.curFilter = null;  
  426.             r.state = BroadcastRecord.IDLE;  
  427.             // 如果跳过,直接继续发送给r所描述的广播转发任务的下一个目标广播接收者处理  
  428.             scheduleBroadcastsLocked();  
  429.             return;  
  430.         }  
  431.   
  432.         r.state = BroadcastRecord.APP_RECEIVE;  
  433.         // 得到静态注册的广播接收者的android:process属性值,即它需要运行在的应用程序进程的名字  
  434.         String targetProcess = info.activityInfo.processName;  
  435.         r.curComponent = component;  
  436.         final int receiverUid = info.activityInfo.applicationInfo.uid;  
  437.         // If it's a singleton, it needs to be the same app or a special app  
  438.         if (r.callingUid != Process.SYSTEM_UID && isSingleton  
  439.                 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {  
  440.             info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);  
  441.         }  
  442.         r.curReceiver = info.activityInfo;  
  443.         if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {  
  444.             Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "  
  445.                     + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "  
  446.                     + info.activityInfo.applicationInfo.uid);  
  447.         }  
  448.   
  449.         if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {  
  450.             scheduleTempWhitelistLocked(receiverUid,  
  451.                     brOptions.getTemporaryAppWhitelistDuration(), r);  
  452.         }  
  453.   
  454.         // Broadcast is being executed, its package can't be stopped.  
  455.         try {  
  456.             AppGlobals.getPackageManager().setPackageStoppedState(  
  457.                     r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));  
  458.         } catch (RemoteException e) {  
  459.         } catch (IllegalArgumentException e) {  
  460.             Slog.w(TAG, "Failed trying to unstop package "  
  461.                     + r.curComponent.getPackageName() + ": " + e);  
  462.         }  
  463.   
  464.         // Is this receiver's application already running?  
  465.         ProcessRecord app = mService.getProcessRecordLocked(targetProcess,  
  466.                 info.activityInfo.applicationInfo.uid, false);  
  467.         // 判断静态注册的广播接收者所运行在的应用程序进程是否已经启动起来  
  468.         if (app != null && app.thread != null) {  
  469.             try {  
  470.                 app.addPackage(info.activityInfo.packageName,  
  471.                         info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);  
  472.                 // 如果已经启动,则直接将广播发送给它处理  
  473.                 processCurBroadcastLocked(r, app);  
  474.                 return;  
  475.             } catch (RemoteException e) {  
  476.                 Slog.w(TAG, "Exception when sending broadcast to "  
  477.                       + r.curComponent, e);  
  478.             } catch (RuntimeException e) {  
  479.                 Slog.wtf(TAG, "Failed sending broadcast to "  
  480.                         + r.curComponent + " with " + r.intent, e);  
  481.                 // If some unexpected exception happened, just skip  
  482.                 // this broadcast.  At this point we are not in the call  
  483.                 // from a client, so throwing an exception out from here  
  484.                 // will crash the entire system instead of just whoever  
  485.                 // sent the broadcast.  
  486.                 logBroadcastReceiverDiscardLocked(r);  
  487.                 finishReceiverLocked(r, r.resultCode, r.resultData,  
  488.                         r.resultExtras, r.resultAbort, false);  
  489.                 scheduleBroadcastsLocked();  
  490.                 // We need to reset the state if we failed to start the receiver.  
  491.                 r.state = BroadcastRecord.IDLE;  
  492.                 return;  
  493.             }  
  494.   
  495.             // If a dead object exception was thrown -- fall through to  
  496.             // restart the application.  
  497.         }  
  498.   
  499.         // Not running -- get it started, to be executed when the app comes up.  
  500.         if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,  
  501.                 "Need to start app ["  
  502.                 + mQueueName + "] " + targetProcess + " for broadcast " + r);  
  503.   
  504.         /*因为下面要开始启动进程了,故这里可以增加禁止自启动判断:如果要启动进程的包名在黑名单中或者不是默认允许启动的,则直接执行启动失败的逻辑*/  
  505.   
  506.         // 调用startProcessLocked方法启动这个应用程序进程  
  507.         if ((r.curApp=mService.startProcessLocked(targetProcess,  
  508.                 info.activityInfo.applicationInfo, true,  
  509.                 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,  
  510.                 "broadcast", r.curComponent,  
  511.                 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0falsefalse))  
  512.                         == null) {  
  513.             // Ah, this recipient is unavailable.  Finish it if necessary,  
  514.             // and mark the broadcast record as ready for the next.  
  515.             Slog.w(TAG, "Unable to launch app "  
  516.                     + info.activityInfo.applicationInfo.packageName + "/"  
  517.                     + info.activityInfo.applicationInfo.uid + " for broadcast "  
  518.                     + r.intent + ": process is bad");  
  519.             logBroadcastReceiverDiscardLocked(r);  
  520.             finishReceiverLocked(r, r.resultCode, r.resultData,  
  521.                     r.resultExtras, r.resultAbort, false);  
  522.             // 如果进程启动失败,继续发送给r所描述的广播转发任务的下一个目标广播接收者处理  
  523.             scheduleBroadcastsLocked();  
  524.             r.state = BroadcastRecord.IDLE;  
  525.             return;  
  526.         }  
  527.   
  528.         // 如果成功启动进程,则保存r和recIdx,表示正在等待r所描述的广播转发任务的  
  529.         // 下一个目标广播接收者所在的应用程序进程启动起来  
  530.         mPendingBroadcast = r;  
  531.         mPendingBroadcastRecvIndex = recIdx;  
  532.     }  
  533. }  


假设r所描述的广播转发任务的下一个目标广播接收者是一个动态注册的广播接收者,那么执行完上面步骤后,接下来就会调用BroadcastQueue类的deliverToRegisteredReceiverLocked方法将一个广播转发给它处理:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private void deliverToRegisteredReceiverLocked(BroadcastRecord r,  
  2.         BroadcastFilter filter, boolean ordered) {  
  3.     boolean skip = false;  
  4.     // BroadcastQueue将一个广播转发给一个目标广播接收者之前,需要检查这个广播的发送者和接收者的权限。  
  5.     // 目标广播接收者所需权限不为null  
  6.     if (filter.requiredPermission != null) {  
  7.         // 根据目标广播接收者所需的权限检验广播的发送者的Pid和Uid是否符合要求  
  8.         int perm = mService.checkComponentPermission(filter.requiredPermission,  
  9.                 r.callingPid, r.callingUid, -1true);  
  10.         // 如果发送者不符合要求,则直接跳过本次转发  
  11.         if (perm != PackageManager.PERMISSION_GRANTED) {  
  12.             Slog.w(TAG, "Permission Denial: broadcasting "  
  13.                     + r.intent.toString()  
  14.                     + " from " + r.callerPackage + " (pid="  
  15.                     + r.callingPid + ", uid=" + r.callingUid + ")"  
  16.                     + " requires " + filter.requiredPermission  
  17.                     + " due to registered receiver " + filter);  
  18.             skip = true;  
  19.         // 如果发送者符合要求,就检查发送者申请的权限是否被用户拒绝,拒绝的话也直接跳过本次转发  
  20.         } else {  
  21.             final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);  
  22.             if (opCode != AppOpsManager.OP_NONE  
  23.                     && mService.mAppOpsService.noteOperation(opCode, r.callingUid,  
  24.                             r.callerPackage) != AppOpsManager.MODE_ALLOWED) {  
  25.                 Slog.w(TAG, "Appop Denial: broadcasting "  
  26.                         + r.intent.toString()  
  27.                         + " from " + r.callerPackage + " (pid="  
  28.                         + r.callingPid + ", uid=" + r.callingUid + ")"  
  29.                         + " requires appop " + AppOpsManager.permissionToOp(  
  30.                                 filter.requiredPermission)  
  31.                         + " due to registered receiver " + filter);  
  32.                 skip = true;  
  33.             }  
  34.         }  
  35.     }  
  36.     // 发送者所需权限不为null  
  37.     if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {  
  38.         // 循环根据发送者所需的权限检验所有的目标广播接收者的Pid和Uid是否符合要求,一项不符合就直接跳过  
  39.         // 符合要求,就检查接收者申请的权限是否被用户拒绝,拒绝的话也直接跳过本次转发  
  40.         for (int i = 0; i < r.requiredPermissions.length; i++) {  
  41.             String requiredPermission = r.requiredPermissions[i];  
  42.             int perm = mService.checkComponentPermission(requiredPermission,  
  43.                     filter.receiverList.pid, filter.receiverList.uid, -1true);  
  44.             if (perm != PackageManager.PERMISSION_GRANTED) {  
  45.                 Slog.w(TAG, "Permission Denial: receiving "  
  46.                         + r.intent.toString()  
  47.                         + " to " + filter.receiverList.app  
  48.                         + " (pid=" + filter.receiverList.pid  
  49.                         + ", uid=" + filter.receiverList.uid + ")"  
  50.                         + " requires " + requiredPermission  
  51.                         + " due to sender " + r.callerPackage  
  52.                         + " (uid " + r.callingUid + ")");  
  53.                 skip = true;  
  54.                 break;  
  55.             }  
  56.             int appOp = AppOpsManager.permissionToOpCode(requiredPermission);  
  57.             if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp  
  58.                     && mService.mAppOpsService.noteOperation(appOp,  
  59.                     filter.receiverList.uid, filter.packageName)  
  60.                     != AppOpsManager.MODE_ALLOWED) {  
  61.                 Slog.w(TAG, "Appop Denial: receiving "  
  62.                         + r.intent.toString()  
  63.                         + " to " + filter.receiverList.app  
  64.                         + " (pid=" + filter.receiverList.pid  
  65.                         + ", uid=" + filter.receiverList.uid + ")"  
  66.                         + " requires appop " + AppOpsManager.permissionToOp(  
  67.                         requiredPermission)  
  68.                         + " due to sender " + r.callerPackage  
  69.                         + " (uid " + r.callingUid + ")");  
  70.                 skip = true;  
  71.                 break;  
  72.             }  
  73.         }  
  74.     }  
  75.     // 如果发送者不需要权限,则检查目标广播接收者的Pid和Uid是否符合要求  
  76.     if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {  
  77.         int perm = mService.checkComponentPermission(null,  
  78.                 filter.receiverList.pid, filter.receiverList.uid, -1true);  
  79.         if (perm != PackageManager.PERMISSION_GRANTED) {  
  80.             Slog.w(TAG, "Permission Denial: security check failed when receiving "  
  81.                     + r.intent.toString()  
  82.                     + " to " + filter.receiverList.app  
  83.                     + " (pid=" + filter.receiverList.pid  
  84.                     + ", uid=" + filter.receiverList.uid + ")"  
  85.                     + " due to sender " + r.callerPackage  
  86.                     + " (uid " + r.callingUid + ")");  
  87.             skip = true;  
  88.         }  
  89.     }  
  90.     if (!skip && r.appOp != AppOpsManager.OP_NONE  
  91.             && mService.mAppOpsService.noteOperation(r.appOp,  
  92.             filter.receiverList.uid, filter.packageName)  
  93.             != AppOpsManager.MODE_ALLOWED) {  
  94.         Slog.w(TAG, "Appop Denial: receiving "  
  95.                 + r.intent.toString()  
  96.                 + " to " + filter.receiverList.app  
  97.                 + " (pid=" + filter.receiverList.pid  
  98.                 + ", uid=" + filter.receiverList.uid + ")"  
  99.                 + " requires appop " + AppOpsManager.opToName(r.appOp)  
  100.                 + " due to sender " + r.callerPackage  
  101.                 + " (uid " + r.callingUid + ")");  
  102.         skip = true;  
  103.     }  
  104.   
  105.     if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,  
  106.             r.callingPid, r.resolvedType, filter.receiverList.uid)) {  
  107.         return;  
  108.     }  
  109.   
  110.     if (filter.receiverList.app == null || filter.receiverList.app.crashing) {  
  111.         Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r  
  112.                 + " to " + filter.receiverList + ": process crashing");  
  113.         skip = true;  
  114.     }  
  115.   
  116.     if (!skip) {  
  117.         // If this is not being sent as an ordered broadcast, then we  
  118.         // don't want to touch the fields that keep track of the current  
  119.         // state of ordered broadcasts.  
  120.         if (ordered) {  
  121.             r.receiver = filter.receiverList.receiver.asBinder();  
  122.             r.curFilter = filter;  
  123.             filter.receiverList.curBroadcast = r;  
  124.             r.state = BroadcastRecord.CALL_IN_RECEIVE;  
  125.             if (filter.receiverList.app != null) {  
  126.                 // Bump hosting application to no longer be in background  
  127.                 // scheduling class.  Note that we can't do that if there  
  128.                 // isn't an app...  but we can only be in that case for  
  129.                 // things that directly call the IActivityManager API, which  
  130.                 // are already core system stuff so don't matter for this.  
  131.                 r.curApp = filter.receiverList.app;  
  132.                 filter.receiverList.app.curReceiver = r;  
  133.                 mService.updateOomAdjLocked(r.curApp);  
  134.             }  
  135.         }  
  136.         try {  
  137.             if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,  
  138.                     "Delivering to " + filter + " : " + r);  
  139.             // 将r所描述的广播转发给filter所描述的目标广播接收者处理  
  140.             performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,  
  141.                     new Intent(r.intent), r.resultCode, r.resultData,  
  142.                     r.resultExtras, r.ordered, r.initialSticky, r.userId);  
  143.             if (ordered) {  
  144.                 r.state = BroadcastRecord.CALL_DONE_RECEIVE;  
  145.             }  
  146.         } catch (RemoteException e) {  
  147.             Slog.w(TAG, "Failure sending broadcast " + r.intent, e);  
  148.             if (ordered) {  
  149.                 r.receiver = null;  
  150.                 r.curFilter = null;  
  151.                 filter.receiverList.curBroadcast = null;  
  152.                 if (filter.receiverList.app != null) {  
  153.                     filter.receiverList.app.curReceiver = null;  
  154.                 }  
  155.             }  
  156.         }  
  157.     }  
  158. }  
  159.   
  160. private static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,  
  161.         Intent intent, int resultCode, String data, Bundle extras,  
  162.         boolean ordered, boolean sticky, int sendingUser) throws RemoteException {  
  163.     // Send the intent to the receiver asynchronously using one-way binder calls.  
  164.     // 如果目标广播接收者需要通过它所运行在的应用程序进程来间接接收广播  
  165.     if (app != null) {  
  166.         if (app.thread != null) {  
  167.             // If we have an app thread, do the call through that so it is  
  168.             // correctly ordered with other one-way calls.  
  169.             // 调用运行在该应用程序进程中的一个ApplicationThread对象的Binder代理对象的  
  170.             // scheduleRegisteredReceiver方法来向它发送这个广播  
  171.             app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,  
  172.                     data, extras, ordered, sticky, sendingUser, app.repProcState);  
  173.         } else {  
  174.             // Application has died. Receiver doesn't exist.  
  175.             throw new RemoteException("app.thread must not be null");  
  176.         }  
  177.     } else {  
  178.         // 否者直接调用与它关联的一个IIntentReceiver对象的Binder代理对象的performReceive方法  
  179.         // 来向它发送这个广播  
  180.         receiver.performReceive(intent, resultCode, data, extras, ordered,  
  181.                 sticky, sendingUser);  
  182.     }  
  183. }  


上面performReceiveLocked方法中的参数app指向一个ProcessRecord对象,用来描述目标广播接收者所运行在的应用程序进程;参数receiver指向了一个实现了IIntentReceiver接口的Binder代理对象,用来描述目标广播接收者;参数intent用来描述即将要发送给目标广播接收者的一个广播。

下面看ActivityThread的内部类ApplicationThread的scheduleRegisteredReceiver方法:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // This function exists to make sure all receiver dispatching is  
  2. // correctly ordered, since these are one-way calls and the binder driver  
  3. // applies transaction ordering per object for such calls.  
  4. public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,  
  5.         int resultCode, String dataStr, Bundle extras, boolean ordered,  
  6.         boolean sticky, int sendingUser, int processState) throws RemoteException {  
  7.     updateProcessState(processState, false);  
  8.     receiver.performReceive(intent, resultCode, dataStr, extras, ordered,  
  9.             sticky, sendingUser);  
  10. }  


参数receiver指向了一个IIntentReceiver对象,前面讲过每一个IIntentReceiver对象在内部都封装了一个广播接收者,并且代替它所封装的广播接收者注册到AMS中。这样当AMS将一个广播发送给一个目标广播接收者时,实际上是将这个广播发送给了与目标广播接收者相关联的一个IIntentReceiver对象,而这个IIntentReceiver对象是通过它的performReceive方法来接收这个广播的。

来看LoadedApk类中的内部类ReceiverDispatcher中的performReceive方法:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. static final class ReceiverDispatcher {  
  2.   
  3.     final static class InnerReceiver extends IIntentReceiver.Stub {  
  4.         final WeakReference<LoadedApk.ReceiverDispatcher> mDispatcher;  
  5.         final LoadedApk.ReceiverDispatcher mStrongRef;  
  6.   
  7.         InnerReceiver(LoadedApk.ReceiverDispatcher rd, boolean strong) {  
  8.             mDispatcher = new WeakReference<LoadedApk.ReceiverDispatcher>(rd);  
  9.             mStrongRef = strong ? rd : null;  
  10.         }  
  11.         public void performReceive(Intent intent, int resultCode, String data,  
  12.                 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {  
  13.             LoadedApk.ReceiverDispatcher rd = mDispatcher.get();  
  14.             if (ActivityThread.DEBUG_BROADCAST) {  
  15.                 int seq = intent.getIntExtra("seq", -1);  
  16.                 Slog.i(ActivityThread.TAG, "Receiving broadcast " + intent.getAction() + " seq=" + seq  
  17.                         + " to " + (rd != null ? rd.mReceiver : null));  
  18.             }  
  19.             if (rd != null) {  
  20.                 // 调用ReceiverDispatcher的performReceive方法来接收intent所描述的广播  
  21.                 rd.performReceive(intent, resultCode, data, extras,  
  22.                         ordered, sticky, sendingUser);  
  23.             } else {  
  24.                 // The activity manager dispatched a broadcast to a registered  
  25.                 // receiver in this process, but before it could be delivered the  
  26.                 // receiver was unregistered.  Acknowledge the broadcast on its  
  27.                 // behalf so that the system's broadcast sequence can continue.  
  28.                 if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,  
  29.                         "Finishing broadcast to unregistered receiver");  
  30.                 IActivityManager mgr = ActivityManagerNative.getDefault();  
  31.                 try {  
  32.                     if (extras != null) {  
  33.                         extras.setAllowFds(false);  
  34.                     }  
  35.                     mgr.finishReceiver(this, resultCode, data, extras, false, intent.getFlags());  
  36.                 } catch (RemoteException e) {  
  37.                     Slog.w(ActivityThread.TAG, "Couldn't finish broadcast to unregistered receiver");  
  38.                 }  
  39.             }  
  40.         }  
  41.     }  
  42.   
  43.     final IIntentReceiver.Stub mIIntentReceiver;  
  44.     // 目标广播接收者  
  45.     final BroadcastReceiver mReceiver;  
  46.     final Context mContext;  
  47.     final Handler mActivityThread;  
  48.     final Instrumentation mInstrumentation;  
  49.     // 目标广播接收者是否已经注册到AMS中  
  50.     final boolean mRegistered;  
  51.     final IntentReceiverLeaked mLocation;  
  52.     RuntimeException mUnregisterLocation;  
  53.     boolean mForgotten;  
  54.   
  55.     final class Args extends BroadcastReceiver.PendingResult implements Runnable {  
  56.         private Intent mCurIntent;  
  57.         private final boolean mOrdered;  
  58.   
  59.         public Args(Intent intent, int resultCode, String resultData, Bundle resultExtras,  
  60.                 boolean ordered, boolean sticky, int sendingUser) {  
  61.             super(resultCode, resultData, resultExtras,  
  62.                     mRegistered ? TYPE_REGISTERED : TYPE_UNREGISTERED, ordered,  
  63.                     sticky, mIIntentReceiver.asBinder(), sendingUser, intent.getFlags());  
  64.             // 要接收的广播  
  65.             mCurIntent = intent;  
  66.             // 描述该广播是否是有序广播  
  67.             mOrdered = ordered;  
  68.         }  
  69.           
  70.         public void run() {  
  71.             // 目标广播接收者  
  72.             final BroadcastReceiver receiver = mReceiver;  
  73.             final boolean ordered = mOrdered;  
  74.               
  75.             if (ActivityThread.DEBUG_BROADCAST) {  
  76.                 int seq = mCurIntent.getIntExtra("seq", -1);  
  77.                 Slog.i(ActivityThread.TAG, "Dispatching broadcast " + mCurIntent.getAction()  
  78.                         + " seq=" + seq + " to " + mReceiver);  
  79.                 Slog.i(ActivityThread.TAG, "  mRegistered=" + mRegistered  
  80.                         + " mOrderedHint=" + ordered);  
  81.             }  
  82.               
  83.             final IActivityManager mgr = ActivityManagerNative.getDefault();  
  84.             final Intent intent = mCurIntent;  
  85.             mCurIntent = null;  
  86.               
  87.             if (receiver == null || mForgotten) {  
  88.                 if (mRegistered && ordered) {  
  89.                     if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,  
  90.                             "Finishing null broadcast to " + mReceiver);  
  91.                     sendFinished(mgr);  
  92.                 }  
  93.                 return;  
  94.             }  
  95.   
  96.             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveReg");  
  97.             try {  
  98.                 ClassLoader cl =  mReceiver.getClass().getClassLoader();  
  99.                 intent.setExtrasClassLoader(cl);  
  100.                 setExtrasClassLoader(cl);  
  101.                 receiver.setPendingResult(this);  
  102.                 // 回调目标广播接收者的onReceive方法来接收这个广播  
  103.                 receiver.onReceive(mContext, intent);  
  104.             } catch (Exception e) {  
  105.                 if (mRegistered && ordered) {  
  106.                     if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,  
  107.                             "Finishing failed broadcast to " + mReceiver);  
  108.                     sendFinished(mgr);  
  109.                 }  
  110.                 if (mInstrumentation == null ||  
  111.                         !mInstrumentation.onException(mReceiver, e)) {  
  112.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  113.                     throw new RuntimeException(  
  114.                         "Error receiving broadcast " + intent  
  115.                         + " in " + mReceiver, e);  
  116.                 }  
  117.             }  
  118.               
  119.             if (receiver.getPendingResult() != null) {  
  120.                 finish();  
  121.             }  
  122.             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  123.         }  
  124.     }  
  125.   
  126.     ReceiverDispatcher(BroadcastReceiver receiver, Context context,  
  127.             Handler activityThread, Instrumentation instrumentation,  
  128.             boolean registered) {  
  129.         if (activityThread == null) {  
  130.             throw new NullPointerException("Handler must not be null");  
  131.         }  
  132.   
  133.         mIIntentReceiver = new InnerReceiver(this, !registered);  
  134.         mReceiver = receiver;  
  135.         mContext = context;  
  136.         mActivityThread = activityThread;  
  137.         mInstrumentation = instrumentation;  
  138.         mRegistered = registered;  
  139.         mLocation = new IntentReceiverLeaked(null);  
  140.         mLocation.fillInStackTrace();  
  141.     }  
  142.   
  143.     . . .  
  144.   
  145.     RuntimeException getUnregisterLocation() {  
  146.         return mUnregisterLocation;  
  147.     }  
  148.   
  149.     public void performReceive(Intent intent, int resultCode, String data,  
  150.             Bundle extras, boolean ordered, boolean sticky, int sendingUser) {  
  151.         if (ActivityThread.DEBUG_BROADCAST) {  
  152.             int seq = intent.getIntExtra("seq", -1);  
  153.             Slog.i(ActivityThread.TAG, "Enqueueing broadcast " + intent.getAction() + " seq=" + seq  
  154.                     + " to " + mReceiver);  
  155.         }  
  156.         // 将参数intent所描述的广播封装成一个Args对象  
  157.         Args args = new Args(intent, resultCode, data, extras, ordered,  
  158.                 sticky, sendingUser);  
  159.         // 将Args对象封装成一个消息发送到目标广播接收者所运行在的应用程序进程的消息队列中,  
  160.         // 这个消息最终在Args类的run方法中处理  
  161.         if (!mActivityThread.post(args)) {  
  162.             if (mRegistered && ordered) {  
  163.                 IActivityManager mgr = ActivityManagerNative.getDefault();  
  164.                 if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,  
  165.                         "Finishing sync broadcast to " + mReceiver);  
  166.                 // 由于这里已经把广播发给接收者处理了,故现在通知AMS继续给下一个目标广播接收者发送广播了  
  167.                 args.sendFinished(mgr);  
  168.             }  
  169.         }  
  170.     }  
  171.   
  172. }  


说到这里,我们分析了动态注册的广播接收者处理有序广播和无序广播的过程,下面说下静态广播的处理过程,看BroadcastQueue类中的processCurBroadcastLocked方法:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private final void processCurBroadcastLocked(BroadcastRecord r,  
  2.         ProcessRecord app) throws RemoteException {  
  3.     if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,  
  4.             "Process cur broadcast " + r + " for app " + app);  
  5.     // 如果目标广播接收者所运行在的应用程序进程没有启动起来,则抛异常  
  6.     if (app.thread == null) {  
  7.         throw new RemoteException();  
  8.     }  
  9.     r.receiver = app.thread.asBinder();  
  10.     r.curApp = app;  
  11.     app.curReceiver = r;  
  12.     app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);  
  13.     mService.updateLruProcessLocked(app, falsenull);  
  14.     mService.updateOomAdjLocked();  
  15.   
  16.     // Tell the application to launch this receiver.  
  17.     r.intent.setComponent(r.curComponent);  
  18.   
  19.     boolean started = false;  
  20.     try {  
  21.         if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,  
  22.                 "Delivering to component " + r.curComponent  
  23.                 + ": " + r);  
  24.         mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());  
  25.   
  26.         // 调用运行在该应用程序进程中的一个ApplicationThread对象的Binder代理对象的  
  27.         // scheduleReceiver方法来向它发送这个广播  
  28.         app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,  
  29.                 mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),  
  30.                 r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,  
  31.                 app.repProcState);  
  32.         if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,  
  33.                 "Process cur broadcast " + r + " DELIVERED for app " + app);  
  34.         started = true;  
  35.     } finally {  
  36.         if (!started) {  
  37.             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,  
  38.                     "Process cur broadcast " + r + ": NOT STARTED!");  
  39.             r.receiver = null;  
  40.             r.curApp = null;  
  41.             app.curReceiver = null;  
  42.         }  
  43.     }  
  44. }  


下面看ActivityThread的内部类ApplicationThread的scheduleReceiver方法:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public final void scheduleReceiver(Intent intent, ActivityInfo info,  
  2.         CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,  
  3.         boolean sync, int sendingUser, int processState) {  
  4.     updateProcessState(processState, false);  
  5.     // 将参数封装成一个ReceiverData对象,通过sendMessage方法向应用程序主线程消息队列中发送一个RECEIVER消息  
  6.     ReceiverData r = new ReceiverData(intent, resultCode, data, extras,  
  7.             sync, false, mAppThread.asBinder(), sendingUser);  
  8.     r.info = info;  
  9.     r.compatInfo = compatInfo;  
  10.     sendMessage(H.RECEIVER, r);  
  11. }  
  12.   
  13. private class H extends Handler {  
  14.     . . .  
  15.     public static final int RECEIVER                = 113;  
  16.   
  17.     public void handleMessage(Message msg) {  
  18.         switch (msg.what) {  
  19.             . . .  
  20.             case RECEIVER:  
  21.                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");  
  22.                 handleReceiver((ReceiverData)msg.obj);  
  23.                 maybeSnapshot();  
  24.                 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  25.                 break;  
  26.         }  
  27.     }  
  28.   
  29. }  
  30.   
  31. private void handleReceiver(ReceiverData data) {  
  32.     // If we are getting ready to gc after going to the background, well  
  33.     // we are back active so skip it.  
  34.     unscheduleGcIdler();  
  35.   
  36.     // 目标广播接收者类名  
  37.     String component = data.intent.getComponent().getClassName();  
  38.   
  39.     LoadedApk packageInfo = getPackageInfoNoCheck(  
  40.             data.info.applicationInfo, data.compatInfo);  
  41.   
  42.     IActivityManager mgr = ActivityManagerNative.getDefault();  
  43.   
  44.     BroadcastReceiver receiver;  
  45.     try {  
  46.         java.lang.ClassLoader cl = packageInfo.getClassLoader();  
  47.         data.intent.setExtrasClassLoader(cl);  
  48.         data.intent.prepareToEnterProcess();  
  49.         data.setExtrasClassLoader(cl);  
  50.         // 根据目标广播接收者类名实例化一个接收对象  
  51.         receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();  
  52.     } catch (Exception e) {  
  53.         if (DEBUG_BROADCAST) Slog.i(TAG,  
  54.                 "Finishing failed broadcast to " + data.intent.getComponent());  
  55.         data.sendFinished(mgr);  
  56.         throw new RuntimeException(  
  57.             "Unable to instantiate receiver " + component  
  58.             + ": " + e.toString(), e);  
  59.     }  
  60.   
  61.     try {  
  62.         Application app = packageInfo.makeApplication(false, mInstrumentation);  
  63.   
  64.         if (localLOGV) Slog.v(  
  65.             TAG, "Performing receive of " + data.intent  
  66.             + ": app=" + app  
  67.             + ", appName=" + app.getPackageName()  
  68.             + ", pkg=" + packageInfo.getPackageName()  
  69.             + ", comp=" + data.intent.getComponent().toShortString()  
  70.             + ", dir=" + packageInfo.getAppDir());  
  71.   
  72.         ContextImpl context = (ContextImpl)app.getBaseContext();  
  73.         sCurrentBroadcastIntent.set(data.intent);  
  74.         receiver.setPendingResult(data);  
  75.         // 回调目标广播接收者的onReceive方法来接收这个广播  
  76.         receiver.onReceive(context.getReceiverRestrictedContext(),  
  77.                 data.intent);  
  78.     } catch (Exception e) {  
  79.         if (DEBUG_BROADCAST) Slog.i(TAG,  
  80.                 "Finishing failed broadcast to " + data.intent.getComponent());  
  81.         data.sendFinished(mgr);  
  82.         if (!mInstrumentation.onException(receiver, e)) {  
  83.             throw new RuntimeException(  
  84.                 "Unable to start receiver " + component  
  85.                 + ": " + e.toString(), e);  
  86.         }  
  87.     } finally {  
  88.         sCurrentBroadcastIntent.set(null);  
  89.     }  
  90.   
  91.     if (receiver.getPendingResult() != null) {  
  92.         // 处理完本次接收后通知AMS继续给下一个目标广播接收者发送广播  
  93.         data.finish();  
  94.     }  
  95. }  


到这里,广播的发送流程就终于分析完了。

内容有理解错误或偏差之处请包涵指正,谢谢!

0 0
原创粉丝点击