当前位置:   article > 正文

Android13 广播发送流程分析_android suppress to broadcast intent

android suppress to broadcast intent

一、广播相关概念

广播分类

1、标准广播:异步广播,广播发出后,所有注册了的广播接收器都会同时接收到该广播。打个比方:做地铁过程中的语音播报,当列车员(广播发出者)进行语音播报(发送广播)时,所有乘客(注册接收该广播的程序)都可以同时听到语音,不分先后顺序。

sendBroadcast(); 

2、有序广播:同步发送,广播发出后,按照注册了的广播接收器的优先级顺序广播,优先级的范围是-1000~1000,数字越大,优先级越高,最先接收到该广播,接收器的优先级通过android:priority设置,并且先收到广播的可以修改或者抛弃该广播,后面优先级小的接收器就无法收到了。同级别的广播,动态优先于静态;同级别同类型的广播,静态:先扫描的优先于后扫描的,动态:先注册的优先于后注册的

sendOrderedBroadcast();

3、粘性广播粘性广播的机制就是发送广播的时候如果没有找到接收器,就会先保存下来,等有广播接收器注册的时候,再把之前保存的广播发出去。因为从Android 5.0(API 21)开始,因为安全性的问题,官方已经正式废弃了粘性广播。

 sendStickyBroadcast();

 广播注册方式
1、动态注册:在Context(即Service或Activity)组件中注册,通过registerReceiver()方法注册,在不使用时取消注册unregisterReceiver()。如果广播发送的时候注册Broadcast的组件没有启动的话,是收不到广播的。

2、 静态注册:在AndroidManifest.xml中注册,并在intent-filter中添加响应的action,并新建一个Broadcast组件类来处理注册广播。如果广播发送的时候Broadcast的组件类进程没有启动的话,会收到广播并启动进程。

具体实现可参考Android的有序广播和无序广播(解决安卓8.0版本之后有序广播的接收问题) 区分了Android8.0前后的实现方式。

前台广播及后台广播
前台广播:在广播发送的时候添加Intent.FLAG_RECEIVER_FOREGROUND flag。
后台广播:在广播发送的时候没有Intent.FLAG_RECEIVER_FOREGROUND flag。

默认情况下,Intent是不带Intent.FLAG_RECEIVER_FOREGROUND 的flag的,所以我们默认使用的都是后台广播。

二、广播发送流程

1、调用ContextImpl的sendBroadcast发送广播

frameworks/base/core/java/android/app/ContextImpl.java

    @Override
    public void sendBroadcast(Intent intent) {
        warnIfCallingFromSystemProcess();
        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
        try {
            //准备离开现有进程
            intent.prepareToLeaveProcess(this);
            //调用 AMS 的broadcastIntentWithFeature方法 
            ActivityManager.getService().broadcastIntentWithFeature(
                    mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
                    null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
                    null, AppOpsManager.OP_NONE, null, false/**表示非有序**/, false/**表示非粘性**/, getUserId());
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }
2、调用AMS的broadcastIntentWithFeature方法 

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

    @Override
    public final int broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId,
            Intent intent, String resolvedType, IIntentReceiver resultTo,
            int resultCode, String resultData, Bundle resultExtras,
            String[] requiredPermissions, String[] excludedPermissions,
            String[] excludedPackages, int appOp, Bundle bOptions,
            boolean serialized, boolean sticky, int userId) {
        enforceNotIsolatedCaller("broadcastIntent");
        synchronized(this) {
            // 验证广播的有效性
            intent = verifyBroadcastLocked(intent);
            final ProcessRecord callerApp = getRecordForAppLOSP(caller);
            final int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();

       //保留原始的origId  
       final long origId = Binder.clearCallingIdentity();

            /// M: DuraSpeed @{
            String suppressAction = mAmsExt.onReadyToStartComponent(
                        callerApp != null ? callerApp.info.packageName : null, callingUid,
                        "broadcast", null);
            if ((suppressAction != null) && suppressAction.equals("skipped")) {
                Binder.restoreCallingIdentity(origId);
                Slog.d(TAG, "broadcastIntentWithFeature, suppress to broadcastIntent!");
                return ActivityManager.BROADCAST_SUCCESS;
            }
            /// @}

            try {
                return broadcastIntentLocked(callerApp,
                        callerApp != null ? callerApp.info.packageName : null, callingFeatureId,
                        intent, resolvedType, resultTo, resultCode, resultData, resultExtras,
                        requiredPermissions, excludedPermissions, excludedPackages, appOp, bOptions,
                        serialized, sticky, callingPid, callingUid, callingUid, callingPid, userId);
            } finally {
                //恢复origId
                Binder.restoreCallingIdentity(origId);
            }
        }
    }

 单独罗列 verifyBroadcastLocked 方法:

    final Intent verifyBroadcastLocked(Intent intent) {
        // Refuse possible leaked file descriptors
        // 拒绝存在有文件描述符的intent
        if (intent != null && intent.hasFileDescriptors() == true) {
            throw new IllegalArgumentException("File descriptors passed in Intent");
        }

        int flags = intent.getFlags();

        if (!mProcessesReady) { //系统还没有准备好,表示还没有调用systemReady 函数.

            // if the caller really truly claims to know what they're doing, go
            // ahead and allow the broadcast without launching any receivers

            if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
                //包含Intent.FLAG_RECEIVER_REGISTERED_ONLY的flag,可以继续往下走.
                // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed.
            } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
                Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
                        + " before boot completion");
                throw new IllegalStateException("Cannot broadcast before boot completed");
            }
        }

        if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
          //禁止携带Intent.FLAG_RECEIVER_BOOT_UPGRADE flag
            throw new IllegalArgumentException(
                    "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
        }

        if ((flags & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
            switch (Binder.getCallingUid()) {
                case ROOT_UID:
                case SHELL_UID:
                    break;
                default:
// 若不是ROOT和SHELL用户,则移除 Intent.FLAG_RECEIVER_FROM_SHELL flag
                    Slog.w(TAG, "Removing FLAG_RECEIVER_FROM_SHELL because caller is UID "
                            + Binder.getCallingUid());
                    intent.removeFlags(Intent.FLAG_RECEIVER_FROM_SHELL);
                    break;
            }
        }

        return intent;
    }

  单独罗列 getRecordForAppLOSP 方法:

    @GuardedBy(anyOf = {"this", "mProcLock"})
    ProcessRecord getRecordForAppLOSP(IApplicationThread thread) {
        if (thread == null) {
            return null;
        }

        ProcessRecord record = mProcessList.getLRURecordForAppLOSP(thread);
        if (record != null) return record;

        // Validation: if it isn't in the LRU list, it shouldn't exist, but let's  double-check that.

        final IBinder threadBinder = thread.asBinder();
        final ArrayMap<String, SparseArray<ProcessRecord>> pmap =
                mProcessList.getProcessNamesLOSP().getMap();

        for (int i = pmap.size()-1; i >= 0; i--) {
            final SparseArray<ProcessRecord> procs = pmap.valueAt(i);
            for (int j = procs.size()-1; j >= 0; j--) {
                final ProcessRecord proc = procs.valueAt(j);
                final IApplicationThread procThread = proc.getThread();
                if (procThread != null && procThread.asBinder() == threadBinder) {
                    Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: "
                            + proc);
                    return proc;
                }
            }
        }

        return null;
    }

3、调用AMS的broadcastIntentLocked方法
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
3.1 系统广播处理broadcastIntentLocked
  1. @GuardedBy("this")
  2. final int broadcastIntentLocked(ProcessRecord callerApp, String callerPackage,
  3. @Nullable String callerFeatureId, Intent intent, String resolvedType,
  4. IIntentReceiver resultTo, int resultCode, String resultData,
  5. Bundle resultExtras, String[] requiredPermissions,
  6. String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions,
  7. boolean ordered, boolean sticky, int callingPid, int callingUid,
  8. int realCallingUid, int realCallingPid, int userId,
  9. boolean allowBackgroundActivityStarts,
  10. @Nullable IBinder backgroundActivityStartsToken,
  11. @Nullable int[] broadcastAllowList) {
  12. intent = new Intent(intent);
  13. //判断是InstantApp
  14. final boolean callerInstantApp = isInstantApp(callerApp, callerPackage, callingUid);
  15. // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS
  16. if (callerInstantApp) {
  17. //取消FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS flag标记
  18. intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
  19. }
  20. if (userId == UserHandle.USER_ALL && broadcastAllowList != null) {
  21. Slog.e(TAG, "broadcastAllowList only applies when sending to individual users. "
  22. + "Assuming restrictive whitelist.");
  23. // userId是USER_ALL ,则不需要此限制.
  24. broadcastAllowList = new int[]{};
  25. }
  26. // By default broadcasts do not go to stopped apps.
  27. //默认情况下,不会像已经停止的应用发送广播.
  28. intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
  29. // If we have not finished booting, don't allow this to launch new processes.
  30. //开机完成之前,不允许开启新的进程.
  31. if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
  32. intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
  33. }
  34. //告知广播的类型
  35. if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
  36. (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
  37. + " ordered=" + ordered + " userid=" + userId);
  38. if ((resultTo != null) && !ordered) {
  39. Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
  40. }
  41. userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
  42. ALLOW_NON_FULL, "broadcast", callerPackage);
  43. // Make sure that the user who is receiving this broadcast or its parent is running.
  44. // If not, we will just skip it. Make an exception for shutdown broadcasts, upgrade steps.
  45. if (userId != UserHandle.USER_ALL && !mUserController.isUserOrItsParentRunning(userId)) {
  46. if ((callingUid != 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 + " and its parent (if any) are stopped");
  51. return ActivityManager.BROADCAST_FAILED_USER_STOPPED;
  52. }
  53. }
  54. final String action = intent.getAction();
  55. BroadcastOptions brOptions = null;
  56. if (bOptions != null) {
  57. brOptions = new BroadcastOptions(bOptions);
  58. if (brOptions.getTemporaryAppAllowlistDuration() > 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. //判断权限是否赋于
  63. if (checkComponentPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
  64. realCallingPid, realCallingUid, -1, true)
  65. != PackageManager.PERMISSION_GRANTED
  66. && checkComponentPermission(START_ACTIVITIES_FROM_BACKGROUND,
  67. realCallingPid, realCallingUid, -1, true)
  68. != PackageManager.PERMISSION_GRANTED
  69. && checkComponentPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND,
  70. realCallingPid, realCallingUid, -1, true)
  71. != PackageManager.PERMISSION_GRANTED) {
  72. String msg = "Permission Denial: " + intent.getAction()
  73. + " broadcast from " + callerPackage + " (pid=" + callingPid
  74. + ", uid=" + callingUid + ")"
  75. + " requires "
  76. + CHANGE_DEVICE_IDLE_TEMP_WHITELIST + " or "
  77. + START_ACTIVITIES_FROM_BACKGROUND + " or "
  78. + START_FOREGROUND_SERVICES_FROM_BACKGROUND;
  79. Slog.w(TAG, msg);
  80. throw new SecurityException(msg);
  81. }
  82. }
  83. // 不能发送给受限的应用
  84. if (brOptions.isDontSendToRestrictedApps()
  85. && !isUidActiveLOSP(callingUid)
  86. && isBackgroundRestrictedNoCheck(callingUid, callerPackage)) {
  87. Slog.i(TAG, "Not sending broadcast " + action + " - app " + callerPackage
  88. + " has background restrictions");
  89. return ActivityManager.START_CANCELED;
  90. }
  91. if (brOptions.allowsBackgroundActivityStarts()) {
  92. // See if the caller is allowed to do this. Note we are checking against
  93. // the actual real caller (not whoever provided the operation as say a
  94. // PendingIntent), because that who is actually supplied the arguments.
  95. //权限没有赋于
  96. if (checkComponentPermission(
  97. android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND,
  98. realCallingPid, realCallingUid, -1, true)
  99. != PackageManager.PERMISSION_GRANTED) {
  100. String msg = "Permission Denial: " + intent.getAction()
  101. + " broadcast from " + callerPackage + " (pid=" + callingPid
  102. + ", uid=" + callingUid + ")"
  103. + " requires "
  104. + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
  105. Slog.w(TAG, msg);
  106. throw new SecurityException(msg);
  107. } else {
  108. allowBackgroundActivityStarts = true;
  109. // We set the token to null since if it wasn't for it we'd allow anyway here
  110. backgroundActivityStartsToken = null;
  111. }
  112. }
  113. }
  114. // Verify that protected broadcasts are only being sent by system code,
  115. // and that system code is only sending protected broadcasts.
  116. final boolean isProtectedBroadcast;
  117. //判断受保护的广播
  118. try {
  119. isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action);
  120. } catch (RemoteException e) {
  121. Slog.w(TAG, "Remote exception", e);
  122. return ActivityManager.BROADCAST_SUCCESS;
  123. }
  124. final boolean isCallerSystem;
  125. switch (UserHandle.getAppId(callingUid)) {
  126. case ROOT_UID:
  127. case SYSTEM_UID:
  128. case PHONE_UID:
  129. case BLUETOOTH_UID:
  130. case NFC_UID:
  131. case SE_UID:
  132. case NETWORK_STACK_UID:
  133. isCallerSystem = true;
  134. break;
  135. default:
  136. //TINNO BEGIN
  137. //DATE20221208, Modify By XIBIN,DGF-1148
  138. isCallerSystem = (callerApp != null) && callerApp.isPersistent()
  139. ||("com.android.systemui".equals(callerPackage) && "com.android.settings.flashlight.action.FLASHLIGHT_CHANGED".equals(action));
  140. //TINNO END
  141. break;
  142. }
  143. // First line security check before anything else: stop non-system apps from sending protected broadcasts.
  144. // 非系统应用阻止发送系统广播
  145. if (!isCallerSystem) {
  146. if (isProtectedBroadcast) {
  147. //非系统应用发送受保护广播,直接报异常
  148. String msg = "Permission Denial: not allowed to send broadcast "
  149. + action + " from pid="
  150. + callingPid + ", uid=" + callingUid;
  151. Slog.w(TAG, msg);
  152. throw new SecurityException(msg);
  153. } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
  154. || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
  155. // Special case for compatibility: we don't want apps to send this,
  156. // but historically it has not been protected and apps may be using it
  157. // to poke their own app widget. So, instead of making it protected,
  158. // just limit it to the caller.
  159. if (callerPackage == null) {
  160. //若找不到广播的调用者,直接报异常.
  161. String msg = "Permission Denial: not allowed to send broadcast "
  162. + action + " from unknown caller.";
  163. Slog.w(TAG, msg);
  164. throw new SecurityException(msg);
  165. } else if (intent.getComponent() != null) {
  166. // They are good enough to send to an explicit component... verify
  167. // it is being sent to the calling app.
  168. //对于ACTION_APPWIDGET_CONFIGURE和ACTION_APPWIDGET_UPDATE 了,两个action,需要调用着和显式组件的包名保持一致.
  169. if (!intent.getComponent().getPackageName().equals(
  170. callerPackage)) {
  171. String msg = "Permission Denial: not allowed to send broadcast "
  172. + action + " to "
  173. + intent.getComponent().getPackageName() + " from "
  174. + callerPackage;
  175. Slog.w(TAG, msg);
  176. throw new SecurityException(msg);
  177. }
  178. } else {
  179. // Limit broadcast to their own package.
  180. //没有现式组件,则默认使用调用者的包名
  181. intent.setPackage(callerPackage);
  182. }
  183. }
  184. }
  185. boolean timeoutExempt = false;
  186. if (action != null) {
  187. //判断是否属于豁免的广播.
  188. if (getBackgroundLaunchBroadcasts().contains(action)) {
  189. if (DEBUG_BACKGROUND_CHECK) {
  190. Slog.i(TAG, "Broadcast action " + action + " forcing include-background");
  191. }
  192. //增加background 应用接收.
  193. intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
  194. }
  195. switch (action) {
  196. case Intent.ACTION_UID_REMOVED:
  197. case Intent.ACTION_PACKAGE_REMOVED:
  198. case Intent.ACTION_PACKAGE_CHANGED:
  199. case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
  200. case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
  201. case Intent.ACTION_PACKAGES_SUSPENDED:
  202. case Intent.ACTION_PACKAGES_UNSUSPENDED:
  203. // Handle special intents: if this broadcast is from the package
  204. // manager about a package being removed, we need to remove all of
  205. // its activities from the history stack.
  206. //若没有赋于权限,则报异常.
  207. if (checkComponentPermission(
  208. android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
  209. callingPid, callingUid, -1, true)
  210. != PackageManager.PERMISSION_GRANTED) {
  211. String msg = "Permission Denial: " + intent.getAction()
  212. + " broadcast from " + callerPackage + " (pid=" + callingPid
  213. + ", uid=" + callingUid + ")"
  214. + " requires "
  215. + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
  216. Slog.w(TAG, msg);
  217. throw new SecurityException(msg);
  218. }
  219. switch (action) {
  220. case Intent.ACTION_UID_REMOVED:
  221. final int uid = getUidFromIntent(intent);
  222. if (uid >= 0) {
  223. mBatteryStatsService.removeUid(uid);
  224. if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
  225. mAppOpsService.resetAllModes(UserHandle.getUserId(uid),
  226. intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME));
  227. } else {
  228. mAppOpsService.uidRemoved(uid);
  229. }
  230. }
  231. break;
  232. case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
  233. // If resources are unavailable just force stop all those packages
  234. // and flush the attribute cache as well.
  235. String list[] =
  236. intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
  237. //将可以用的应用进行force stop
  238. if (list != null && list.length > 0) {
  239. for (int i = 0; i < list.length; i++) {
  240. forceStopPackageLocked(list[i], -1, false, true, true,
  241. false, false, userId, "storage unmount");
  242. }
  243. //清理 recent task
  244. mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
  245. //触发GC清理.
  246. sendPackageBroadcastLocked(
  247. ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE,
  248. list, userId);
  249. }
  250. break;
  251. case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
  252. mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
  253. break;
  254. case Intent.ACTION_PACKAGE_REMOVED:
  255. case Intent.ACTION_PACKAGE_CHANGED:
  256. Uri data = intent.getData();
  257. String ssp;
  258. if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
  259. boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action);
  260. final boolean replacing =
  261. intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
  262. final boolean killProcess =
  263. !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false);
  264. final boolean fullUninstall = removed && !replacing;
  265. if (removed) {
  266. if (killProcess) {
  267. forceStopPackageLocked(ssp, UserHandle.getAppId(
  268. intent.getIntExtra(Intent.EXTRA_UID, -1)),
  269. false, true, true, false, fullUninstall, userId,
  270. removed ? "pkg removed" : "pkg changed");
  271. } else {
  272. // Kill any app zygotes always, since they can't fork new
  273. // processes with references to the old code
  274. forceStopAppZygoteLocked(ssp, UserHandle.getAppId(
  275. intent.getIntExtra(Intent.EXTRA_UID, -1)),
  276. userId);
  277. }
  278. final int cmd = killProcess
  279. ? ApplicationThreadConstants.PACKAGE_REMOVED
  280. : ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL;
  281. sendPackageBroadcastLocked(cmd,
  282. new String[] {ssp}, userId);
  283. //完全卸载
  284. if (fullUninstall) {
  285. mAppOpsService.packageRemoved(
  286. intent.getIntExtra(Intent.EXTRA_UID, -1), ssp);
  287. // Remove all permissions granted from/to this package
  288. //撤销赋于的权限
  289. mUgmInternal.removeUriPermissionsForPackage(ssp, userId,
  290. true, false);
  291. //移除recent task mAtmInternal.removeRecentTasksByPackageName(ssp, userId);
  292. // force stop 对应的package
  293. mServices.forceStopPackageLocked(ssp, userId);
  294. //卸载对应的应用
  295. mAtmInternal.onPackageUninstalled(ssp);
  296. //记录卸载信息
  297. mBatteryStatsService.notePackageUninstalled(ssp);
  298. }
  299. } else {
  300. if (killProcess) {
  301. final int extraUid = intent.getIntExtra(Intent.EXTRA_UID,
  302. -1);
  303. synchronized (mProcLock) {
  304. //杀掉对应的进程
  305. mProcessList.killPackageProcessesLSP(ssp,
  306. UserHandle.getAppId(extraUid),
  307. userId, ProcessList.INVALID_ADJ,
  308. ApplicationExitInfo.REASON_USER_REQUESTED,
  309. ApplicationExitInfo.SUBREASON_UNKNOWN,
  310. "change " + ssp);
  311. }
  312. }
  313. //清理disable的包名
  314. cleanupDisabledPackageComponentsLocked(ssp, userId,
  315. intent.getStringArrayExtra(
  316. Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST));
  317. //处理所有此packagename的service
  318. mServices.schedulePendingServiceStartLocked(ssp, userId);
  319. }
  320. }
  321. break;
  322. case Intent.ACTION_PACKAGES_SUSPENDED:
  323. case Intent.ACTION_PACKAGES_UNSUSPENDED:
  324. final boolean suspended = Intent.ACTION_PACKAGES_SUSPENDED.equals(
  325. intent.getAction());
  326. final String[] packageNames = intent.getStringArrayExtra(
  327. Intent.EXTRA_CHANGED_PACKAGE_LIST);
  328. final int userIdExtra = intent.getIntExtra(
  329. Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
  330. mAtmInternal.onPackagesSuspendedChanged(packageNames, suspended,
  331. userIdExtra);
  332. break;
  333. }
  334. break;
  335. case Intent.ACTION_PACKAGE_REPLACED:
  336. {
  337. final Uri data = intent.getData();
  338. final String ssp;
  339. if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
  340. ApplicationInfo aInfo = null;
  341. try {
  342. aInfo = AppGlobals.getPackageManager()
  343. .getApplicationInfo(ssp, STOCK_PM_FLAGS, userId);
  344. } catch (RemoteException ignore) {}
  345. if (aInfo == null) {
  346. Slog.w(TAG, "Dropping ACTION_PACKAGE_REPLACED for non-existent pkg:"
  347. + " ssp=" + ssp + " data=" + data);
  348. return ActivityManager.BROADCAST_SUCCESS;
  349. }
  350. updateAssociationForApp(aInfo);
  351. mAtmInternal.onPackageReplaced(aInfo);
  352. mServices.updateServiceApplicationInfoLocked(aInfo);
  353. sendPackageBroadcastLocked(ApplicationThreadConstants.PACKAGE_REPLACED,
  354. new String[] {ssp}, userId);
  355. }
  356. break;
  357. }
  358. case Intent.ACTION_PACKAGE_ADDED:
  359. {
  360. // Special case for adding a package: by default turn on compatibility mode.
  361. Uri data = intent.getData();
  362. String ssp;
  363. if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
  364. final boolean replacing =
  365. intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
  366. mAtmInternal.onPackageAdded(ssp, replacing);
  367. try {
  368. ApplicationInfo ai = AppGlobals.getPackageManager().
  369. getApplicationInfo(ssp, STOCK_PM_FLAGS, 0);
  370. mBatteryStatsService.notePackageInstalled(ssp,
  371. ai != null ? ai.longVersionCode : 0);
  372. } catch (RemoteException e) {
  373. }
  374. }
  375. break;
  376. }
  377. case Intent.ACTION_PACKAGE_DATA_CLEARED:
  378. {
  379. Uri data = intent.getData();
  380. String ssp;
  381. if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
  382. mAtmInternal.onPackageDataCleared(ssp);
  383. }
  384. break;
  385. }
  386. case Intent.ACTION_TIMEZONE_CHANGED:
  387. // If this is the time zone changed action, queue up a message that will reset
  388. // the timezone of all currently running processes. This message will get
  389. // queued up before the broadcast happens.
  390. mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
  391. break;
  392. case Intent.ACTION_TIME_CHANGED:
  393. // EXTRA_TIME_PREF_24_HOUR_FORMAT is optional so we must distinguish between
  394. // the tri-state value it may contain and "unknown".
  395. // For convenience we re-use the Intent extra values.
  396. final int NO_EXTRA_VALUE_FOUND = -1;
  397. final int timeFormatPreferenceMsgValue = intent.getIntExtra(
  398. Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT,
  399. NO_EXTRA_VALUE_FOUND /* defaultValue */);
  400. // Only send a message if the time preference is available.
  401. if (timeFormatPreferenceMsgValue != NO_EXTRA_VALUE_FOUND) {
  402. Message updateTimePreferenceMsg =
  403. mHandler.obtainMessage(UPDATE_TIME_PREFERENCE_MSG,
  404. timeFormatPreferenceMsgValue, 0);
  405. mHandler.sendMessage(updateTimePreferenceMsg);
  406. }
  407. mBatteryStatsService.noteCurrentTimeChanged();
  408. break;
  409. case ConnectivityManager.ACTION_CLEAR_DNS_CACHE:
  410. mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG);
  411. break;
  412. case Proxy.PROXY_CHANGE_ACTION:
  413. mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG));
  414. break;
  415. case android.hardware.Camera.ACTION_NEW_PICTURE:
  416. case android.hardware.Camera.ACTION_NEW_VIDEO:
  417. // In N we just turned these off; in O we are turing them back on partly,
  418. // only for registered receivers. This will still address the main problem
  419. // (a spam of apps waking up when a picture is taken putting significant
  420. // memory pressure on the system at a bad point), while still allowing apps
  421. // that are already actively running to know about this happening.
  422. intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
  423. break;
  424. case android.security.KeyChain.ACTION_TRUST_STORE_CHANGED:
  425. mHandler.sendEmptyMessage(HANDLE_TRUST_STORAGE_UPDATE_MSG);
  426. break;
  427. case "com.android.launcher.action.INSTALL_SHORTCUT":
  428. // As of O, we no longer support this broadcasts, even for pre-O apps.
  429. // Apps should now be using ShortcutManager.pinRequestShortcut().
  430. Log.w(TAG, "Broadcast " + action
  431. + " no longer supported. It will not be delivered.");
  432. return ActivityManager.BROADCAST_SUCCESS;
  433. case Intent.ACTION_PRE_BOOT_COMPLETED:
  434. timeoutExempt = true;
  435. break;
  436. case Intent.ACTION_CLOSE_SYSTEM_DIALOGS:
  437. if (!mAtmInternal.checkCanCloseSystemDialogs(callingPid, callingUid,
  438. callerPackage)) {
  439. // Returning success seems to be the pattern here
  440. return ActivityManager.BROADCAST_SUCCESS;
  441. }
  442. break;
  443. }
  444. if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
  445. Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
  446. Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
  447. final int uid = getUidFromIntent(intent);
  448. if (uid != -1) {
  449. final UidRecord uidRec = mProcessList.getUidRecordLOSP(uid);
  450. if (uidRec != null) {
  451. uidRec.updateHasInternetPermission();
  452. }
  453. }
  454. }
  455. }
  456. // Add to the sticky list if requested.
  457. //粘性广播
  458. if (sticky) {
  459. //判断是否赋于BROADCAST_STICKY 权限
  460. if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
  461. callingPid, callingUid)
  462. != PackageManager.PERMISSION_GRANTED) {
  463. String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
  464. + callingPid + ", uid=" + callingUid
  465. + " requires " + android.Manifest.permission.BROADCAST_STICKY;
  466. Slog.w(TAG, msg);
  467. throw new SecurityException(msg);
  468. }
  469. //粘性广播不需要对应的权限
  470. if (requiredPermissions != null && requiredPermissions.length > 0) {
  471. Slog.w(TAG, "Can't broadcast sticky intent " + intent
  472. + " and enforce permissions " + Arrays.toString(requiredPermissions));
  473. return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
  474. }
  475. //粘性广播不需要指明组件
  476. if (intent.getComponent() != null) {
  477. throw new SecurityException(
  478. "Sticky broadcasts can't target a specific component");
  479. }
  480. // We use userId directly here, since the "all" target is maintained
  481. // as a separate set of sticky broadcasts.
  482. if (userId != UserHandle.USER_ALL) {
  483. // But first, if this is not a broadcast to all users, then
  484. // make sure it doesn't conflict with an existing broadcast to
  485. // all users.
  486. ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
  487. UserHandle.USER_ALL);
  488. if (stickies != null) {
  489. ArrayList<Intent> list = stickies.get(intent.getAction());
  490. if (list != null) {
  491. int N = list.size();
  492. int i;
  493. for (i=0; i<N; i++) {
  494. if (intent.filterEquals(list.get(i))) {
  495. //若粘性广播在队里里面,则报冲突
  496. throw new IllegalArgumentException(
  497. "Sticky broadcast " + intent + " for user "
  498. + userId + " conflicts with existing global broadcast");
  499. }
  500. }
  501. }
  502. }
  503. }
  504. ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
  505. if (stickies == null) {
  506. stickies = new ArrayMap<>();
  507. mStickyBroadcasts.put(userId, stickies);
  508. }
  509. ArrayList<Intent> list = stickies.get(intent.getAction());
  510. if (list == null) {
  511. list = new ArrayList<>();
  512. stickies.put(intent.getAction(), list);
  513. }
  514. final int stickiesCount = list.size();
  515. int i;
  516. for (i = 0; i < stickiesCount; i++) {
  517. if (intent.filterEquals(list.get(i))) {
  518. //若在userId中的队列,出现重复,则替换
  519. // This sticky already exists, replace it.
  520. list.set(i, new Intent(intent));
  521. break;
  522. }
  523. }
  524. if (i >= stickiesCount) {
  525. list.add(new Intent(intent));
  526. }
  527. }
  528. int[] users;
  529. if (userId == UserHandle.USER_ALL) {
  530. // Caller wants broadcast to go to all started users.
  531. users = mUserController.getStartedUserArray();
  532. } else {
  533. // Caller wants broadcast to go to one specific user.
  534. users = new int[] {userId};
  535. }
  536. // Figure out who all will receive this broadcast.
  537. //寻找所有接收广播的接收者
  538. List receivers = null;
  539. List<BroadcastFilter> registeredReceivers = null;
  540. // Need to resolve the intent to interested receivers...
  541. if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
  542. == 0) {
  543. //在PMS中去查询对应的广播接收者,获取静态广播接受者的列表
  544. receivers = collectReceiverComponents(
  545. intent, resolvedType, callingUid, users, broadcastAllowList);
  546. }
  547. if (intent.getComponent() == null) {
  548. //若不指定广播接收者.则会遍历所有符合条件的接收者
  549. if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) {
  550. // Query one target user at a time, excluding shell-restricted users
  551. for (int i = 0; i < users.length; i++) {
  552. if (mUserController.hasUserRestriction(
  553. UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) {
  554. continue;
  555. }
  556. //查看动态广播接收者
  557. List<BroadcastFilter> registeredReceiversForUser =
  558. mReceiverResolver.queryIntent(intent,
  559. resolvedType, false /*defaultOnly*/, users[i]);
  560. if (registeredReceivers == null) {
  561. registeredReceivers = registeredReceiversForUser;
  562. } else if (registeredReceiversForUser != null) {
  563. registeredReceivers.addAll(registeredReceiversForUser);
  564. }
  565. }
  566. } else {
  567. //查看动态广播接收者
  568. registeredReceivers = mReceiverResolver.queryIntent(intent,
  569. resolvedType, false /*defaultOnly*/, userId);
  570. }
  571. }
  572. //支持替换旧的广播
  573. final boolean replacePending =
  574. (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
  575. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction()
  576. + " replacePending=" + replacePending);
  577. if (registeredReceivers != null && broadcastAllowList != null) {
  578. // if a uid whitelist was provided, remove anything in the application space that wasn't
  579. // in it.
  580. for (int i = registeredReceivers.size() - 1; i >= 0; i--) {
  581. final int owningAppId = UserHandle.getAppId(registeredReceivers.get(i).owningUid);
  582. if (owningAppId >= Process.FIRST_APPLICATION_UID
  583. && Arrays.binarySearch(broadcastAllowList, owningAppId) < 0) {
  584. registeredReceivers.remove(i);
  585. }
  586. }
  587. }
  588. int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
  589. if (!ordered && NR > 0) {
  590. // If we are not serializing this broadcast, then send the
  591. // registered receivers separately so they don't wait for the
  592. // components to be launched.
  593. //针对非有序广播,进行并发发送广播.
  594. if (isCallerSystem) {
  595. //对应system的调用者进行验证
  596. checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
  597. isProtectedBroadcast, registeredReceivers);
  598. }
  599. final BroadcastQueue queue = broadcastQueueForIntent(intent);
  600. BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
  601. callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
  602. requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions,
  603. registeredReceivers, resultTo, resultCode, resultData, resultExtras, ordered,
  604. sticky, false, userId, allowBackgroundActivityStarts,
  605. backgroundActivityStartsToken, timeoutExempt);
  606. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r);
  607. final boolean replaced = replacePending
  608. && (queue.replaceParallelBroadcastLocked(r) != null);
  609. // Note: We assume resultTo is null for non-ordered broadcasts.
  610. if (!replaced) {
  611. //若不进行旧的广播替换,则开始加入队列进行并行分发.
  612. queue.enqueueParallelBroadcastLocked(r);
  613. //安排广播分发
  614. queue.scheduleBroadcastsLocked();
  615. }
  616. //表示处理完成,则将动态广播接收者进行清空.
  617. registeredReceivers = null;
  618. NR = 0;
  619. }
  620. // Merge into one list.
  621. // 合并动态和静态广播接收者
  622. int ir = 0;
  623. if (receivers != null) {
  624. // A special case for PACKAGE_ADDED: do not allow the package
  625. // being added to see this broadcast. This prevents them from
  626. // using this as a back door to get run as soon as they are
  627. // installed. Maybe in the future we want to have a special install
  628. // broadcast or such for apps, but we'd like to deliberately make
  629. // this decision.
  630. //过滤ACTION_PACKAGE_ADDED , ACTION_PACKAGE_RESTARTED 和ACTION_PACKAGE_DATA_CLEARED 对应包名
  631. String skipPackages[] = null;
  632. if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
  633. || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
  634. || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
  635. Uri data = intent.getData();
  636. if (data != null) {
  637. String pkgName = data.getSchemeSpecificPart();
  638. if (pkgName != null) {
  639. skipPackages = new String[] { pkgName };
  640. }
  641. }
  642. } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
  643. skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
  644. }
  645. if (skipPackages != null && (skipPackages.length > 0)) {
  646. for (String skipPackage : skipPackages) {
  647. if (skipPackage != null) {
  648. int NT = receivers.size();
  649. for (int it=0; it<NT; it++) {
  650. ResolveInfo curt = (ResolveInfo)receivers.get(it);
  651. if (curt.activityInfo.packageName.equals(skipPackage)) {
  652. receivers.remove(it);
  653. it--;
  654. NT--;
  655. }
  656. }
  657. }
  658. }
  659. }
  660. int NT = receivers != null ? receivers.size() : 0;
  661. int it = 0;
  662. ResolveInfo curt = null;
  663. BroadcastFilter curr = null;
  664. while (it < NT && ir < NR) {
  665. if (curt == null) {
  666. //先在静态广播中获取
  667. curt = (ResolveInfo)receivers.get(it);
  668. }
  669. if (curr == null) {
  670. //其次在动态广播中获取
  671. curr = registeredReceivers.get(ir);
  672. }
  673. if (curr.getPriority() >= curt.priority) {
  674. //同样的优先级,动态广播优先于静态广播
  675. // Insert this broadcast record into the final list.
  676. receivers.add(it, curr);
  677. ir++;
  678. curr = null;
  679. it++;
  680. NT++;
  681. } else {
  682. // Skip to the next ResolveInfo in the final list.
  683. it++;
  684. curt = null;
  685. }
  686. }
  687. }
  688. //将所有的动态广播插入final receivers 中
  689. while (ir < NR) {
  690. if (receivers == null) {
  691. receivers = new ArrayList();
  692. }
  693. receivers.add(registeredReceivers.get(ir));
  694. ir++;
  695. }
  696. if (isCallerSystem) {
  697. checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
  698. isProtectedBroadcast, receivers);
  699. }
  700. if ((receivers != null && receivers.size() > 0)
  701. || resultTo != null) {
  702. //
  703. BroadcastQueue queue = broadcastQueueForIntent(intent);
  704. BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
  705. callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
  706. requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions,
  707. receivers, resultTo, resultCode, resultData, resultExtras,
  708. ordered, sticky, false, userId, allowBackgroundActivityStarts,
  709. backgroundActivityStartsToken, timeoutExempt);
  710. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r);
  711. final BroadcastRecord oldRecord =
  712. replacePending ? queue.replaceOrderedBroadcastLocked(r) : null;
  713. if (oldRecord != null) {
  714. // Replaced, fire the result-to receiver.
  715. if (oldRecord.resultTo != null) {
  716. final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent);
  717. try {
  718. //若替代的广播,则更新old的队列
  719. oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo,
  720. oldRecord.intent,
  721. Activity.RESULT_CANCELED, null, null,
  722. false, false, oldRecord.userId);
  723. } catch (RemoteException e) {
  724. Slog.w(TAG, "Failure ["
  725. + queue.mQueueName + "] sending broadcast result of "
  726. + intent, e);
  727. }
  728. }
  729. } else {
  730. //分发有序广播
  731. queue.enqueueOrderedBroadcastLocked(r);
  732. queue.scheduleBroadcastsLocked();
  733. }
  734. } else {
  735. // There was nobody interested in the broadcast, but we still want to record
  736. // that it happened.
  737. if (intent.getComponent() == null && intent.getPackage() == null
  738. && (intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
  739. // This was an implicit broadcast... let's record it for posterity.
  740. addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0);
  741. }
  742. }
  743. return ActivityManager.BROADCAST_SUCCESS;
  744. }

小结:

(1) 对粘性广播的处理过程。把粘性广播放在了list列表中,而list以action为键放置在了stickies中,而stickies又以userId为键放在了mStickyBroadcasts中,因此mStickyBroadcasts保存了设备中所有用户粘性广播的Intent相关信息。

(2)静态和动态注册的接收器

[1] 上面这段代码主要是获取静态和动态注册的接收器。其中receivers 表示静态注册接收器列表, registeredReceivers 表示动态注册接收器列表;
[2] Intent.FLAG_RECEIVER_REGISTERED_ONLY该flag表示仅支持动态注册,不支持静态注册,如果在manifest中注册是收不到该广播的;
[3] 如果发送广播不加Component信息会遍历获取所有的当前intent的接收者,因此如果定向发给某个应用的话,要把Component信息加上。

(3) 无序动态注册接收器添加到并发列表中

  [1] 上面这段代码是,如果发送的是无序广播,且存在动态注册的广播接收者,就将该广播加入并行处理队列,并进行一次广播发送。简单来说就是【动态注册且接受无序广播的广播接收者】是并行操作,广播发送速度会比较快。
 [2]  Intent.FLAG_RECEIVER_REPLACE_PENDING 该flag表示是否替换待发出的广播,如果flag为1会进行替换, 位置与待发广播一样。

(4)合并有序动态注册和静态注册接收器

 [1] 上面这段代码主要是对【动态注册接受有序广播的广播接收者】和【静态注册的广播接收者】进行合并,如果是有序广播,动态接收者和静态的接收者合并到一个队列里面进行处理,也就是说order广播下,所有的接收者(静态和动态)处理方式都是一样的,都是串行处理;
 [2] 对于静态注册的接收者而言,始终是和order广播的处理方式是一样的,也就是说静态的接收者只有order模式(串行化接收);
 [3] 在合并过程中,如果一个动态注册的广播接收者和一个静态注册的目标广播接收者的优先级相同,那么动态注册的目标接收者会排在静态注册的目标广播接收者前面,即动态注册的目标广播接收者会优先于静态注册的广播接收者接收到有序广播
 

(5)系统广播处理broadcastIntentLocked函数这部分代码逻辑总结:

首先是判断是不是系统广播,也就是switch语句中的部分,这部分的广播是系统发出的,根据不同广播做出不同的处理,系统广播我们可以接收但是不能发送,只能由系统发出;
接着是粘性广播的处理;
然后是【动态注册且接受无序广播的广播接收者】的处理,把他们放入到BroadcastQueue的mParallelBroadcasts中,并调用scheduleBroadcastsLocked,BroadcastQueue对mParallelBroadcasts列表中条目的最终处理是通过并行操作来完成的;
最后是【动态注册接受有序广播的广播接收者】和【静态注册的广播接收者】的处理,把他们放入到BroadcastQueue的mOrderedBroadcasts中,并调用scheduleBroadcastsLocked,BroadcastQueue对mOrderedBroadcasts列表中条目的最终处理是通过串行操作来完成的;

4、BroadcastQueue广播处理
    4.1 BroadcastQueue队列定义及入队列方法判断

frameworks/base/services/core/java/com/android/server/am/BroadcastQueue.java

    /**
     * Lists of all active broadcasts that are to be executed immediately
     * (without waiting for another broadcast to finish).  Currently this only
     * contains broadcasts to registered receivers, to avoid spinning up
     * a bunch of processes to execute IntentReceiver components.  Background-
     * and foreground-priority broadcasts are queued separately.
     */
    final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
    /**
     * Tracking of the ordered broadcast queue, including deferral policy and alarm
     * prioritization.
     */
    final BroadcastDispatcher mDispatcher;

在广播队列中定义了两个处理列表,一个是并发处理列表mParallelBroadcasts,一个是有序处理列表mDispatcher

  1. BroadcastQueue broadcastQueueForIntent(Intent intent) {
  2. if (isOnOffloadQueue(intent.getFlags())) {
  3. if (DEBUG_BROADCAST_BACKGROUND) {
  4. Slog.i(TAG_BROADCAST,
  5. "Broadcast intent " + intent + " on offload queue");
  6. }
  7. return mOffloadBroadcastQueue;
  8. }
  9. final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
  10. if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST,
  11. "Broadcast intent " + intent + " on "
  12. + (isFg ? "foreground" : "background") + " queue");
  13. return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
  14. }
  15. public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
  16. mParallelBroadcasts.add(r);
  17. enqueueBroadcastHelper(r);
  18. }
  19. public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
  20. mDispatcher.enqueueOrderedBroadcastLocked(r);
  21. enqueueBroadcastHelper(r);
  22. }

上面的三个方法是上面源码中出现的,broadcastQueueForIntent根据intent是否含有Intent.FLAG_RECEIVER_FOREGROUND来判断是前台广播还是普通后台广播,如果是前台广播返回前台广播处队列。如果是普通后台广播返回后台广播处理队列。

获取队列后,将发给【动态注册且接受无序广播的广播接收者】的广播通过enqueueParallelBroadcastLocked函数添加到该队列的并发处理列表中。将发给【动态注册接受有序广播的广播接收者】和【静态注册的广播接收者】的广播通过enqueueOrderedBroadcastLocked函数添加到该队列的有序处理列表中。

4.2 BroadcastQueue队列中广播发送流程

从上面的源码分析中看到最后我们都执行了scheduleBroadcastsLocked对广播进行了进一步发送处理,接下来看下这个函数的逻辑。

  1. public void scheduleBroadcastsLocked() {
  2. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
  3. + mQueueName + "]: current="
  4. + mBroadcastsScheduled);
  5. if (mBroadcastsScheduled) {
  6. //若正在调度中,则取消本地调度
  7. return;
  8. }
  9. mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
  10. mBroadcastsScheduled = true;
  11. }
  12. private final class BroadcastHandler extends Handler {
  13. public BroadcastHandler(Looper looper) {
  14. super(looper, null, true);
  15. }
  16. @Override
  17. public void handleMessage(Message msg) {
  18. switch (msg.what) {
  19. case BROADCAST_INTENT_MSG: {
  20. if (DEBUG_BROADCAST) Slog.v(
  21. TAG_BROADCAST, "Received BROADCAST_INTENT_MSG ["
  22. + mQueueName + "]");
  23. //开始处理广播
  24. processNextBroadcast(true);
  25. } break;
  26. case BROADCAST_TIMEOUT_MSG: {
  27. synchronized (mService) {
  28. broadcastTimeoutLocked(true);
  29. }
  30. } break;
  31. }
  32. }
  33. }

先判断mBroadcastsScheduled的值,如果true说明消息队列已经存在一个类型为BROADCAST_INTENT_MSG的消息了,直接返回,因为该消息在执行完毕会自动调用下一条消息;
接下来广播的处理逻辑会走到 processNextBroadcast函数中,下面来看下该函数的逻辑。
 

  1. private void processNextBroadcast(boolean fromMsg) {
  2. synchronized (mService) {
  3. processNextBroadcastLocked(fromMsg, false);
  4. }
  5. }

详细分析 processNextBroadcastLocked 函数:

  1. final void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) {
  2. BroadcastRecord r;
  3. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
  4. + mQueueName + "]: "
  5. + mParallelBroadcasts.size() + " parallel broadcasts; "
  6. + mDispatcher.describeStateLocked());
  7. //更新CPU统计信息
  8. mService.updateCpuStats();
  9. if (fromMsg) {
  10. //来自于BROADCAST_INTENT_MSG, 说明广播已经在处理,可以将此变量标记为false
  11. mBroadcastsScheduled = false;
  12. }
  13. // First, deliver any non-serialized broadcasts right away.
  14. // 无序广播之间不存在相互等待,这里处理的是保存在无序广播调度队列mParallelBroadcasts中的广播发送任务,
  15. // 即把保存在无序广播调度队列mParallelBroadcasts中的广播发送给它的目标广播接收者处理
  16. while (mParallelBroadcasts.size() > 0) {
  17. r = mParallelBroadcasts.remove(0);
  18. r.dispatchTime = SystemClock.uptimeMillis();
  19. r.dispatchClockTime = System.currentTimeMillis();
  20. if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
  21. Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
  22. createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
  23. System.identityHashCode(r));
  24. Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
  25. createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
  26. System.identityHashCode(r));
  27. }
  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. //通过deliverToRegisteredReceiverLocked调用ActivityThread.scheduleRegisteredReceiver处理广播
  37. deliverToRegisteredReceiverLocked(r,
  38. (BroadcastFilter) target, false, i);
  39. }
  40. //记录在历史列表中.
  41. addBroadcastToHistoryLocked(r);
  42. if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
  43. + mQueueName + "] " + r);
  44. }
  45. // Now take care of the next serialized one...
  46. // If we are waiting for a process to come up to handle the next
  47. // broadcast, then do nothing at this point. Just in case, we
  48. // check that the process we're waiting for still exists.
  49. //接下来处理有序广播
  50. if (mPendingBroadcast != null) {
  51. if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
  52. "processNextBroadcast [" + mQueueName + "]: waiting for "
  53. + mPendingBroadcast.curApp);
  54. boolean isDead;
  55. //等待Broadcast有对应的pid
  56. if (mPendingBroadcast.curApp.getPid() > 0) {
  57. synchronized (mService.mPidsSelfLocked) {
  58. ProcessRecord proc = mService.mPidsSelfLocked.get(
  59. mPendingBroadcast.curApp.getPid());
  60. //等待广播接收者,是否存在或者已经发生了crash
  61. isDead = proc == null || proc.mErrorState.isCrashing();
  62. }
  63. } else {
  64. //若没有获取到当前等待广播的pid,则通过进程名称进行搜索.
  65. final ProcessRecord proc = mService.mProcessList.getProcessNamesLOSP().get(
  66. mPendingBroadcast.curApp.processName, mPendingBroadcast.curApp.uid);
  67. //判断接收者是否还存在
  68. isDead = proc == null || !proc.isPendingStart();
  69. }
  70. if (!isDead) {
  71. // It's still alive, so keep waiting
  72. //若接收者存在,则继续保持. 如果应用已经启动,会调用AMS的函数来处理静态广播,这里直接return
  73. return;
  74. } else {
  75. Slog.w(TAG, "pending app ["
  76. + mQueueName + "]" + mPendingBroadcast.curApp
  77. + " died before responding to broadcast");
  78. //若不存在,则记录为idle状态
  79. mPendingBroadcast.state = BroadcastRecord.IDLE;
  80. mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
  81. mPendingBroadcast = null;
  82. }
  83. }
  84. boolean looped = false;
  85. do {
  86. final long now = SystemClock.uptimeMillis();
  87. //获取当前时间的BroadcastRecord
  88. r = mDispatcher.getNextBroadcastLocked(now);
  89. if (r == null) {
  90. // No more broadcasts are deliverable right now, so all done!
  91. //没有获取到BroadcastRecord, 说明已经处理完成.
  92. //安排延迟广播检查
  93. mDispatcher.scheduleDeferralCheckLocked(false);
  94. synchronized (mService.mAppProfiler.mProfilerLock) {
  95. //触发GC
  96. mService.mAppProfiler.scheduleAppGcsLPf();
  97. }
  98. if (looped && !skipOomAdj) {
  99. // If we had finished the last ordered broadcast, then
  100. // make sure all processes have correct oom and sched
  101. // adjustments.
  102. //更新ADJ
  103. mService.updateOomAdjPendingTargetsLocked(
  104. OomAdjuster.OOM_ADJ_REASON_START_RECEIVER);
  105. }
  106. // when we have no more ordered broadcast on this queue, stop logging
  107. //因为已经处理完成广播,停止日志记录.
  108. if (mService.mUserController.mBootCompleted && mLogLatencyMetrics) {
  109. mLogLatencyMetrics = false;
  110. }
  111. return;
  112. }
  113. boolean forceReceive = false;
  114. // Ensure that even if something goes awry with the timeout
  115. // detection, we catch "hung" broadcasts here, discard them,
  116. // and continue to make progress.
  117. //
  118. // This is only done if the system is ready so that early-stage receivers
  119. // don't get executed with timeouts; and of course other timeout-
  120. // exempt broadcasts are ignored.
  121. int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
  122. if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) {
  123. //超时广播强制执行
  124. if ((numReceivers > 0) &&
  125. (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers)) &&
  126. /// M: ANR Debug Mechanism
  127. !mService.mAnrManager.isAnrDeferrable()) {
  128. Slog.w(TAG, "Hung broadcast ["
  129. + mQueueName + "] discarded after timeout failure:"
  130. + " now=" + now
  131. + " dispatchTime=" + r.dispatchTime
  132. + " startTime=" + r.receiverTime
  133. + " intent=" + r.intent
  134. + " numReceivers=" + numReceivers
  135. + " nextReceiver=" + r.nextReceiver
  136. + " state=" + r.state);
  137. //出现超时,强制结束
  138. broadcastTimeoutLocked(false); // forcibly finish this broadcast // 重置参数,继续处理有序广播调度队列mOrderedBroadcasts的下一个广播转发任务
  139. forceReceive = true;
  140. r.state = BroadcastRecord.IDLE;
  141. }
  142. }
  143. if (r.state != BroadcastRecord.IDLE) {
  144. //广播不处于IDLE 状态,则直接返回.
  145. if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
  146. "processNextBroadcast("
  147. + mQueueName + ") called when not idle (state="
  148. + r.state + ")");
  149. return;
  150. }
  151. // Is the current broadcast is done for any reason?
  152. if (r.receivers == null || r.nextReceiver >= numReceivers
  153. || r.resultAbort || forceReceive) {
  154. // Send the final result if requested
  155. if (r.resultTo != null) {
  156. boolean sendResult = true;
  157. // if this was part of a split/deferral complex, update the refcount and only
  158. // send the completion when we clear all of them
  159. if (r.splitToken != 0) {
  160. int newCount = mSplitRefcounts.get(r.splitToken) - 1;
  161. if (newCount == 0) {
  162. // done! clear out this record's bookkeeping and deliver
  163. if (DEBUG_BROADCAST_DEFERRAL) {
  164. Slog.i(TAG_BROADCAST,
  165. "Sending broadcast completion for split token "
  166. + r.splitToken + " : " + r.intent.getAction());
  167. }
  168. mSplitRefcounts.delete(r.splitToken);
  169. } else {
  170. // still have some split broadcast records in flight; update refcount
  171. // and hold off on the callback
  172. if (DEBUG_BROADCAST_DEFERRAL) {
  173. Slog.i(TAG_BROADCAST,
  174. "Result refcount now " + newCount + " for split token "
  175. + r.splitToken + " : " + r.intent.getAction()
  176. + " - not sending completion yet");
  177. }
  178. sendResult = false;
  179. mSplitRefcounts.put(r.splitToken, newCount);
  180. }
  181. }
  182. if (sendResult) {
  183. if (r.callerApp != null) {
  184. mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(
  185. r.callerApp);
  186. }
  187. try {
  188. if (DEBUG_BROADCAST) {
  189. Slog.i(TAG_BROADCAST, "Finishing broadcast [" + mQueueName + "] "
  190. + r.intent.getAction() + " app=" + r.callerApp);
  191. }
  192. performReceiveLocked(r.callerApp, r.resultTo,
  193. new Intent(r.intent), r.resultCode,
  194. r.resultData, r.resultExtras, false, false, r.userId);
  195. // Set this to null so that the reference
  196. // (local and remote) isn't kept in the mBroadcastHistory.
  197. r.resultTo = null;
  198. } catch (RemoteException e) {
  199. r.resultTo = null;
  200. Slog.w(TAG, "Failure ["
  201. + mQueueName + "] sending broadcast result of "
  202. + r.intent, e);
  203. }
  204. }
  205. }
  206. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
  207. //取消广播超时
  208. cancelBroadcastTimeoutLocked();
  209. if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
  210. "Finished with ordered broadcast " + r);
  211. // ... and on to the next...
  212. //添加在历史记录里面
  213. addBroadcastToHistoryLocked(r);
  214. if (r.intent.getComponent() == null && r.intent.getPackage() == null
  215. && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
  216. // This was an implicit broadcast... let's record it for posterity.
  217. mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
  218. r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
  219. }
  220. mDispatcher.retireBroadcastLocked(r);
  221. r = null;
  222. looped = true;
  223. continue;
  224. }
  225. // Check whether the next receiver is under deferral policy, and handle that
  226. // accordingly. If the current broadcast was already part of deferred-delivery
  227. // tracking, we know that it must now be deliverable as-is without re-deferral.
  228. if (!r.deferred) {
  229. final int receiverUid = r.getReceiverUid(r.receivers.get(r.nextReceiver));
  230. if (mDispatcher.isDeferringLocked(receiverUid)) {
  231. if (DEBUG_BROADCAST_DEFERRAL) {
  232. Slog.i(TAG_BROADCAST, "Next receiver in " + r + " uid " + receiverUid
  233. + " at " + r.nextReceiver + " is under deferral");
  234. }
  235. // If this is the only (remaining) receiver in the broadcast, "splitting"
  236. // doesn't make sense -- just defer it as-is and retire it as the
  237. // currently active outgoing broadcast.
  238. BroadcastRecord defer;
  239. if (r.nextReceiver + 1 == numReceivers) {
  240. if (DEBUG_BROADCAST_DEFERRAL) {
  241. Slog.i(TAG_BROADCAST, "Sole receiver of " + r
  242. + " is under deferral; setting aside and proceeding");
  243. }
  244. defer = r;
  245. mDispatcher.retireBroadcastLocked(r);
  246. } else {
  247. // Nontrivial case; split out 'uid's receivers to a new broadcast record
  248. // and defer that, then loop and pick up continuing delivery of the current
  249. // record (now absent those receivers).
  250. // The split operation is guaranteed to match at least at 'nextReceiver'
  251. defer = r.splitRecipientsLocked(receiverUid, r.nextReceiver);
  252. if (DEBUG_BROADCAST_DEFERRAL) {
  253. Slog.i(TAG_BROADCAST, "Post split:");
  254. Slog.i(TAG_BROADCAST, "Original broadcast receivers:");
  255. for (int i = 0; i < r.receivers.size(); i++) {
  256. Slog.i(TAG_BROADCAST, " " + r.receivers.get(i));
  257. }
  258. Slog.i(TAG_BROADCAST, "Split receivers:");
  259. for (int i = 0; i < defer.receivers.size(); i++) {
  260. Slog.i(TAG_BROADCAST, " " + defer.receivers.get(i));
  261. }
  262. }
  263. // Track completion refcount as well if relevant
  264. if (r.resultTo != null) {
  265. int token = r.splitToken;
  266. if (token == 0) {
  267. // first split of this record; refcount for 'r' and 'deferred'
  268. r.splitToken = defer.splitToken = nextSplitTokenLocked();
  269. mSplitRefcounts.put(r.splitToken, 2);
  270. if (DEBUG_BROADCAST_DEFERRAL) {
  271. Slog.i(TAG_BROADCAST,
  272. "Broadcast needs split refcount; using new token "
  273. + r.splitToken);
  274. }
  275. } else {
  276. // new split from an already-refcounted situation; increment count
  277. final int curCount = mSplitRefcounts.get(token);
  278. if (DEBUG_BROADCAST_DEFERRAL) {
  279. if (curCount == 0) {
  280. Slog.wtf(TAG_BROADCAST,
  281. "Split refcount is zero with token for " + r);
  282. }
  283. }
  284. mSplitRefcounts.put(token, curCount + 1);
  285. if (DEBUG_BROADCAST_DEFERRAL) {
  286. Slog.i(TAG_BROADCAST, "New split count for token " + token
  287. + " is " + (curCount + 1));
  288. }
  289. }
  290. }
  291. }
  292. mDispatcher.addDeferredBroadcast(receiverUid, defer);
  293. r = null;
  294. looped = true;
  295. continue;
  296. }
  297. }
  298. } while (r == null);
  299. // Get the next receiver...
  300. //获取下一个将要处理的广播接收者在其列表中的位置
  301. int recIdx = r.nextReceiver++;
  302. // Keep track of when this receiver started, and make sure there
  303. // is a timeout message pending to kill it if need be.
  304. //记录receiver 时间
  305. r.receiverTime = SystemClock.uptimeMillis();
  306. if (recIdx == 0) {
  307. //记录分发时间戳,便于判断超时
  308. r.dispatchTime = r.receiverTime;
  309. r.dispatchClockTime = System.currentTimeMillis();
  310. if (mLogLatencyMetrics) {
  311. FrameworkStatsLog.write(
  312. FrameworkStatsLog.BROADCAST_DISPATCH_LATENCY_REPORTED,
  313. r.dispatchClockTime - r.enqueueClockTime);
  314. }
  315. if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
  316. Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
  317. createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
  318. System.identityHashCode(r));
  319. Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
  320. createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
  321. System.identityHashCode(r));
  322. }
  323. if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
  324. + mQueueName + "] " + r);
  325. }
  326. if (! mPendingBroadcastTimeoutMessage) {
  327. long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
  328. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
  329. "Submitting BROADCAST_TIMEOUT_MSG ["
  330. + mQueueName + "] for " + r + " at " + timeoutTime);
  331. //设置ANR的超时时间. 在这里可以为某个应用定制ANR 时间.
  332. setBroadcastTimeoutLocked(timeoutTime);
  333. }
  334. final BroadcastOptions brOptions = r.options;
  335. final Object nextReceiver = r.receivers.get(recIdx);
  336. // 如果当前nextReceiver是一个BroadcastFilter类型,说明是一个动态注册接收者,不需要启动一个进程
  337. if (nextReceiver instanceof BroadcastFilter) {
  338. // Simple case: this is a registered receiver who gets
  339. // a direct call.
  340. BroadcastFilter filter = (BroadcastFilter)nextReceiver;
  341. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
  342. "Delivering ordered ["
  343. + mQueueName + "] to registered "
  344. + filter + ": " + r);
  345. // 调用deliverToRegisteredReceiverLocked向所有的receivers发送广播
  346. // 将它所描述的每一个无序广播发送给每一个广播接收者,异步处理广播
  347. // 通过deliverToRegisteredReceiverLocked调用
  348. deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
  349. if (r.receiver == null || !r.ordered) {
  350. // The receiver has already finished, so schedule to
  351. // process the next one.
  352. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
  353. + mQueueName + "]: ordered="
  354. + r.ordered + " receiver=" + r.receiver);
  355. r.state = BroadcastRecord.IDLE;
  356. scheduleBroadcastsLocked();
  357. } else {
  358. if (filter.receiverList != null) {
  359. maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
  360. // r is guaranteed ordered at this point, so we know finishReceiverLocked()
  361. // will get a callback and handle the activity start token lifecycle.
  362. }
  363. }
  364. return;
  365. }
  366. // Hard case: need to instantiate the receiver, possibly
  367. // starting its application process to host it.
  368. // 如果上面if没有进行拦截,说明不是广播接收者动态注册的,而应该是静态注册的
  369. // 此时进程可能没有启动
  370. ResolveInfo info =
  371. (ResolveInfo)nextReceiver;
  372. ComponentName component = new ComponentName(
  373. info.activityInfo.applicationInfo.packageName,
  374. info.activityInfo.name);
  375. boolean skip = false;
  376. if (brOptions != null &&
  377. (info.activityInfo.applicationInfo.targetSdkVersion
  378. < brOptions.getMinManifestReceiverApiLevel() ||
  379. info.activityInfo.applicationInfo.targetSdkVersion
  380. > brOptions.getMaxManifestReceiverApiLevel())) {
  381. //不符合要求直接跳过
  382. Slog.w(TAG, "Target SDK mismatch: receiver " + info.activityInfo
  383. + " targets " + info.activityInfo.applicationInfo.targetSdkVersion
  384. + " but delivery restricted to ["
  385. + brOptions.getMinManifestReceiverApiLevel() + ", "
  386. + brOptions.getMaxManifestReceiverApiLevel()
  387. + "] broadcasting " + broadcastDescription(r, component));
  388. skip = true;
  389. }
  390. if (!skip && !mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
  391. component.getPackageName(), info.activityInfo.applicationInfo.uid)) {
  392. Slog.w(TAG, "Association not allowed: broadcasting "
  393. + broadcastDescription(r, component));
  394. skip = true;
  395. }
  396. if (!skip) {
  397. skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
  398. r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
  399. if (skip) {
  400. Slog.w(TAG, "Firewall blocked: broadcasting "
  401. + broadcastDescription(r, component));
  402. }
  403. }
  404. int perm = mService.checkComponentPermission(info.activityInfo.permission,
  405. r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
  406. info.activityInfo.exported);
  407. if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
  408. if (!info.activityInfo.exported) {
  409. Slog.w(TAG, "Permission Denial: broadcasting "
  410. + broadcastDescription(r, component)
  411. + " is not exported from uid " + info.activityInfo.applicationInfo.uid);
  412. } else {
  413. Slog.w(TAG, "Permission Denial: broadcasting "
  414. + broadcastDescription(r, component)
  415. + " requires " + info.activityInfo.permission);
  416. }
  417. skip = true;
  418. } else if (!skip && info.activityInfo.permission != null) {
  419. final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
  420. if (opCode != AppOpsManager.OP_NONE && mService.getAppOpsManager().noteOpNoThrow(opCode,
  421. r.callingUid, r.callerPackage, r.callerFeatureId,
  422. "Broadcast delivered to " + info.activityInfo.name)
  423. != AppOpsManager.MODE_ALLOWED) {
  424. Slog.w(TAG, "Appop Denial: broadcasting "
  425. + broadcastDescription(r, component)
  426. + " requires appop " + AppOpsManager.permissionToOp(
  427. info.activityInfo.permission));
  428. skip = true;
  429. }
  430. }
  431. boolean isSingleton = false;
  432. try {
  433. isSingleton = mService.isSingleton(info.activityInfo.processName,
  434. info.activityInfo.applicationInfo,
  435. info.activityInfo.name, info.activityInfo.flags);
  436. } catch (SecurityException e) {
  437. Slog.w(TAG, e.getMessage());
  438. skip = true;
  439. }
  440. if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
  441. if (ActivityManager.checkUidPermission(
  442. android.Manifest.permission.INTERACT_ACROSS_USERS,
  443. info.activityInfo.applicationInfo.uid)
  444. != PackageManager.PERMISSION_GRANTED) {
  445. Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
  446. + " requests FLAG_SINGLE_USER, but app does not hold "
  447. + android.Manifest.permission.INTERACT_ACROSS_USERS);
  448. skip = true;
  449. }
  450. }
  451. if (!skip && info.activityInfo.applicationInfo.isInstantApp()
  452. && r.callingUid != info.activityInfo.applicationInfo.uid) {
  453. Slog.w(TAG, "Instant App Denial: receiving "
  454. + r.intent
  455. + " to " + component.flattenToShortString()
  456. + " due to sender " + r.callerPackage
  457. + " (uid " + r.callingUid + ")"
  458. + " Instant Apps do not support manifest receivers");
  459. skip = true;
  460. }
  461. if (!skip && r.callerInstantApp
  462. && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0
  463. && r.callingUid != info.activityInfo.applicationInfo.uid) {
  464. Slog.w(TAG, "Instant App Denial: receiving "
  465. + r.intent
  466. + " to " + component.flattenToShortString()
  467. + " requires receiver have visibleToInstantApps set"
  468. + " due to sender " + r.callerPackage
  469. + " (uid " + r.callingUid + ")");
  470. skip = true;
  471. }
  472. if (r.curApp != null && r.curApp.mErrorState.isCrashing()) {
  473. // If the target process is crashing, just skip it.
  474. Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
  475. + " to " + r.curApp + ": process crashing");
  476. skip = true;
  477. }
  478. if (!skip) {
  479. boolean isAvailable = false;
  480. try {
  481. isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
  482. info.activityInfo.packageName,
  483. UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
  484. } catch (Exception e) {
  485. // all such failures mean we skip this receiver
  486. Slog.w(TAG, "Exception getting recipient info for "
  487. + info.activityInfo.packageName, e);
  488. }
  489. if (!isAvailable) {
  490. Slog.w(TAG_BROADCAST,
  491. "Skipping delivery to " + info.activityInfo.packageName + " / "
  492. + info.activityInfo.applicationInfo.uid
  493. + " : package no longer available");
  494. skip = true;
  495. }
  496. }
  497. // If permissions need a review before any of the app components can run, we drop
  498. // the broadcast and if the calling app is in the foreground and the broadcast is
  499. // explicit we launch the review UI passing it a pending intent to send the skipped
  500. // broadcast.
  501. if (!skip) {
  502. if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
  503. info.activityInfo.packageName, UserHandle.getUserId(
  504. info.activityInfo.applicationInfo.uid))) {
  505. Slog.w(TAG_BROADCAST,
  506. "Skipping delivery: permission review required for "
  507. + broadcastDescription(r, component));
  508. skip = true;
  509. }
  510. }
  511. // This is safe to do even if we are skipping the broadcast, and we need
  512. // this information now to evaluate whether it is going to be allowed to run.
  513. final int receiverUid = info.activityInfo.applicationInfo.uid;
  514. // If it's a singleton, it needs to be the same app or a special app
  515. if (r.callingUid != Process.SYSTEM_UID && isSingleton
  516. && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
  517. info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
  518. }
  519. // 得到ResolveInfo对象info所描述的广播接收者的android:process属性值,
  520. // 即它需要运行在的应用程序进程的名称,并且保存在变量targetProcess中
  521. String targetProcess = info.activityInfo.processName;
  522. // 获取当前广播接收者的进程记录,也就是该静态广播接收者是否已经运行
  523. ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
  524. info.activityInfo.applicationInfo.uid);
  525. if (!skip) {
  526. final int allowed = mService.getAppStartModeLOSP(
  527. info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
  528. info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false);
  529. if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
  530. // We won't allow this receiver to be launched if the app has been
  531. // completely disabled from launches, or it was not explicitly sent
  532. // to it and the app is in a state that should not receive it
  533. // (depending on how getAppStartModeLOSP has determined that).
  534. if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
  535. Slog.w(TAG, "Background execution disabled: receiving "
  536. + r.intent + " to "
  537. + component.flattenToShortString());
  538. skip = true;
  539. } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
  540. || (r.intent.getComponent() == null
  541. && r.intent.getPackage() == null
  542. && ((r.intent.getFlags()
  543. & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
  544. && !isSignaturePerm(r.requiredPermissions))) {
  545. mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
  546. component.getPackageName());
  547. Slog.w(TAG, "Background execution not allowed: receiving "
  548. + r.intent + " to "
  549. + component.flattenToShortString());
  550. skip = true;
  551. }
  552. }
  553. }
  554. if (!skip && !Intent.ACTION_SHUTDOWN.equals(r.intent.getAction())
  555. && !mService.mUserController
  556. .isUserRunning(UserHandle.getUserId(info.activityInfo.applicationInfo.uid),
  557. 0 /* flags */)) {
  558. skip = true;
  559. Slog.w(TAG,
  560. "Skipping delivery to " + info.activityInfo.packageName + " / "
  561. + info.activityInfo.applicationInfo.uid + " : user is not running");
  562. }
  563. /// M: DuraSpeed @{
  564. boolean isSuppress = false;
  565. isSuppress = mService.mAmsExt.onBeforeStartProcessForStaticReceiver(
  566. info.activityInfo.packageName);
  567. if (isSuppress) {
  568. //快霸进行定制
  569. Slog.d(TAG, "processNextBroadcastLocked, suppress to start process of staticReceiver"
  570. + " for package:" + info.activityInfo.packageName);
  571. skip = true;
  572. }
  573. /// @}
  574. if (!skip && r.excludedPermissions != null && r.excludedPermissions.length > 0) {
  575. for (int i = 0; i < r.excludedPermissions.length; i++) {
  576. String excludedPermission = r.excludedPermissions[i];
  577. try {
  578. perm = AppGlobals.getPackageManager()
  579. .checkPermission(excludedPermission,
  580. info.activityInfo.applicationInfo.packageName,
  581. UserHandle
  582. .getUserId(info.activityInfo.applicationInfo.uid));
  583. } catch (RemoteException e) {
  584. perm = PackageManager.PERMISSION_DENIED;
  585. }
  586. int appOp = AppOpsManager.permissionToOpCode(excludedPermission);
  587. if (appOp != AppOpsManager.OP_NONE) {
  588. // When there is an app op associated with the permission,
  589. // skip when both the permission and the app op are
  590. // granted.
  591. if ((perm == PackageManager.PERMISSION_GRANTED) && (
  592. mService.getAppOpsManager().checkOpNoThrow(appOp,
  593. info.activityInfo.applicationInfo.uid,
  594. info.activityInfo.packageName)
  595. == AppOpsManager.MODE_ALLOWED)) {
  596. skip = true;
  597. break;
  598. }
  599. } else {
  600. // When there is no app op associated with the permission,
  601. // skip when permission is granted.
  602. if (perm == PackageManager.PERMISSION_GRANTED) {
  603. skip = true;
  604. break;
  605. }
  606. }
  607. }
  608. }
  609. // Check that the receiver does *not* belong to any of the excluded packages
  610. if (!skip && r.excludedPackages != null && r.excludedPackages.length > 0) {
  611. if (ArrayUtils.contains(r.excludedPackages, component.getPackageName())) {
  612. Slog.w(TAG, "Skipping delivery of excluded package "
  613. + r.intent + " to "
  614. + component.flattenToShortString()
  615. + " excludes package " + component.getPackageName()
  616. + " due to sender " + r.callerPackage
  617. + " (uid " + r.callingUid + ")");
  618. skip = true;
  619. }
  620. }
  621. if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
  622. r.requiredPermissions != null && r.requiredPermissions.length > 0) {
  623. for (int i = 0; i < r.requiredPermissions.length; i++) {
  624. String requiredPermission = r.requiredPermissions[i];
  625. try {
  626. perm = AppGlobals.getPackageManager().
  627. checkPermission(requiredPermission,
  628. info.activityInfo.applicationInfo.packageName,
  629. UserHandle
  630. .getUserId(info.activityInfo.applicationInfo.uid));
  631. } catch (RemoteException e) {
  632. perm = PackageManager.PERMISSION_DENIED;
  633. }
  634. if (perm != PackageManager.PERMISSION_GRANTED) {
  635. Slog.w(TAG, "Permission Denial: receiving "
  636. + r.intent + " to "
  637. + component.flattenToShortString()
  638. + " requires " + requiredPermission
  639. + " due to sender " + r.callerPackage
  640. + " (uid " + r.callingUid + ")");
  641. skip = true;
  642. break;
  643. }
  644. int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
  645. if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp) {
  646. if (!noteOpForManifestReceiver(appOp, r, info, component)) {
  647. skip = true;
  648. break;
  649. }
  650. }
  651. }
  652. }
  653. if (!skip && r.appOp != AppOpsManager.OP_NONE) {
  654. if (!noteOpForManifestReceiver(r.appOp, r, info, component)) {
  655. skip = true;
  656. }
  657. }
  658. if (skip) {
  659. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
  660. "Skipping delivery of ordered [" + mQueueName + "] "
  661. + r + " for reason described above");
  662. r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
  663. r.receiver = null;
  664. r.curFilter = null;
  665. r.state = BroadcastRecord.IDLE;
  666. r.manifestSkipCount++;
  667. scheduleBroadcastsLocked();
  668. return;
  669. }
  670. r.manifestCount++;
  671. r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
  672. r.state = BroadcastRecord.APP_RECEIVE;
  673. r.curComponent = component;
  674. r.curReceiver = info.activityInfo;
  675. if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
  676. Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
  677. + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
  678. + receiverUid);
  679. }
  680. final boolean isActivityCapable =
  681. (brOptions != null && brOptions.getTemporaryAppAllowlistDuration() > 0);
  682. //临时白名单
  683. maybeScheduleTempAllowlistLocked(receiverUid, r, brOptions);
  684. // Report that a component is used for explicit broadcasts.
  685. if (r.intent.getComponent() != null && r.curComponent != null
  686. && !TextUtils.equals(r.curComponent.getPackageName(), r.callerPackage)) {
  687. //记录显式广播
  688. mService.mUsageStatsService.reportEvent(
  689. r.curComponent.getPackageName(), r.userId, Event.APP_COMPONENT_USED);
  690. }
  691. // Broadcast is being executed, its package can't be stopped.
  692. try {
  693. //广播被接收,不能将接收者设置为stop 状态.
  694. AppGlobals.getPackageManager().setPackageStoppedState(
  695. r.curComponent.getPackageName(), false, r.userId);
  696. } catch (RemoteException e) {
  697. } catch (IllegalArgumentException e) {
  698. Slog.w(TAG, "Failed trying to unstop package "
  699. + r.curComponent.getPackageName() + ": " + e);
  700. }
  701. // Is this receiver's application already running?
  702. //判断当前接收者的应用是否在运行.
  703. if (app != null && app.getThread() != null && !app.isKilled()) {
  704. try {
  705. app.addPackage(info.activityInfo.packageName,
  706. info.activityInfo.applicationInfo.longVersionCode, mService.mProcessStats);
  707. maybeAddAllowBackgroundActivityStartsToken(app, r);
  708. //处理当前广播
  709. // app进程存在,通过processCurBroadcastLocked -> ActivityThread.scheduleReceiver -> receiver.onReceive处理当前广播
  710. processCurBroadcastLocked(r, app);
  711. //若进程还是一直活着,当前接收者处理完成,直接结束
  712. // 静态广播是order广播是一种同步处理方式,因此处理完可以直接return
  713. return;
  714. } catch (RemoteException e) {
  715. Slog.w(TAG, "Exception when sending broadcast to "
  716. + r.curComponent, e);
  717. } catch (RuntimeException e) {
  718. Slog.wtf(TAG, "Failed sending broadcast to "
  719. + r.curComponent + " with " + r.intent, e);
  720. // If some unexpected exception happened, just skip
  721. // this broadcast. At this point we are not in the call
  722. // from a client, so throwing an exception out from here
  723. // will crash the entire system instead of just whoever
  724. // sent the broadcast.
  725. logBroadcastReceiverDiscardLocked(r);
  726. finishReceiverLocked(r, r.resultCode, r.resultData,
  727. r.resultExtras, r.resultAbort, false);
  728. scheduleBroadcastsLocked();
  729. // We need to reset the state if we failed to start the receiver.
  730. r.state = BroadcastRecord.IDLE;
  731. return;
  732. }
  733. // If a dead object exception was thrown -- fall through to
  734. // restart the application.
  735. }
  736. // Not running -- get it started, to be executed when the app comes up.
  737. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
  738. "Need to start app ["
  739. + mQueueName + "] " + targetProcess + " for broadcast " + r);
  740. //当前接收者应用没有存活,则直接启动它.
  741. r.curApp = mService.startProcessLocked(targetProcess,
  742. info.activityInfo.applicationInfo, true,
  743. r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
  744. new HostingRecord("broadcast", r.curComponent), isActivityCapable
  745. ? ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE : ZYGOTE_POLICY_FLAG_EMPTY,
  746. (r.intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false);
  747. //启动应用失败.
  748. if (r.curApp == null) {
  749. // Ah, this recipient is unavailable. Finish it if necessary,
  750. // and mark the broadcast record as ready for the next.
  751. //若启动失败,则丢失信息,并记录.
  752. Slog.w(TAG, "Unable to launch app "
  753. + info.activityInfo.applicationInfo.packageName + "/"
  754. + receiverUid + " for broadcast "
  755. + r.intent + ": process is bad");
  756. logBroadcastReceiverDiscardLocked(r);
  757. finishReceiverLocked(r, r.resultCode, r.resultData,
  758. r.resultExtras, r.resultAbort, false);
  759. scheduleBroadcastsLocked();
  760. r.state = BroadcastRecord.IDLE;
  761. return;
  762. }
  763. // 将BroadcastRecord赋值为mPendingBroadcast,等待应用启动完成后处理
  764. // 正在启动接收者进程,将正在启动的BroadcastRecord记录存储到mPendingBroadcast中,同时将当前正在
  765. // 启动的接收者进程在所有接收者中的索引存储到mPendingBroadcastRecvIndex,如果当前广播接收者处理
  766. // 完,需要继续从mPendingBroadcastRecvIndex计算到下一个接收者发送当前广播
  767. maybeAddAllowBackgroundActivityStartsToken(r.curApp, r);
  768. mPendingBroadcast = r;
  769. mPendingBroadcastRecvIndex = recIdx;
  770. }

(1)上面这段代码逻辑:对并行处理列表中的广播调用deliverToRegisteredReceiverLocked将每一个无序广播发送给每一个广播接收者,异步处理广播。注意入参ordered值为false

(2)上面这段代码是在处理广播前对一些特殊情况进行处理,例如,处理列表为空,直接返回;当前广播正在处理中返回;下一个接收者为空或者当前接受者设置了resultAbort 等异常情况处理。

(3)上面代码开始对广播进行处理,先进行了计时操作,然后根据接收者不同,先对动态注册接收器进行处理(BroadcastFilter类型)。逻辑最后通过deliverToRegisteredReceiverLocked调用ActivityThread.scheduleRegisteredReceiver处理广播。上面有分析这个函数,此时入参orderedtrue,用来执行动态注册的广播接收者的发送接收过程。
 

4.2.2.2 静态接收器的处理

上面代码是对静态广播的处理,静态广播又分为两种,静态接收者所在进程是启动状态,静态接收者所在进程是未启动状态。根据所在进程的启动状态分别来进行处理。

app进程存在,通过processCurBroadcastLocked -> ActivityThread.scheduleReceiver -> receiver.onReceive处理当前广播。

app进程不存在,会先创建该进程。
 

APP存在,调用BroadcastQueue的processCurBroadcastLocked方法处理有序广播

  1. private final void processCurBroadcastLocked(BroadcastRecord r,
  2. ProcessRecord app) throws RemoteException {
  3. //LOG打印
  4. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
  5. "Process cur broadcast " + r + " for app " + app);
  6. final IApplicationThread thread = app.getThread();
  7. if (thread == null) {
  8. //若没有找到ApplicationThread 对象,则报异常.
  9. throw new RemoteException();
  10. }
  11. if (app.isInFullBackup()) {
  12. //若是FULL备份,则忽略此广播
  13. skipReceiverLocked(r);
  14. return;
  15. }
  16. // 将进程的相关信息写入当前BroadcastRecord中相关的接收者
  17. r.receiver = thread.asBinder();
  18. r.curApp = app;
  19. final ProcessReceiverRecord prr = app.mReceivers;
  20. prr.addCurReceiver(r);
  21. app.mState.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
  22. mService.updateLruProcessLocked(app, false, null);
  23. // Make sure the oom adj score is updated before delivering the broadcast.
  24. // Force an update, even if there are other pending requests, overall it still saves time,
  25. // because time(updateOomAdj(N apps)) <= N * time(updateOomAdj(1 app)).
  26. mService.enqueueOomAdjTargetLocked(app);
  27. mService.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_START_RECEIVER);
  28. // Tell the application to launch this receiver.
  29. //告知启动的组件
  30. r.intent.setComponent(r.curComponent);
  31. boolean started = false;
  32. try {
  33. if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
  34. "Delivering to component " + r.curComponent
  35. + ": " + r);
  36. mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
  37. PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
  38. //处理广播发送.
  39. thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
  40. mService.compatibilityInfoForPackage(r.curReceiver.applicationInfo),
  41. r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
  42. app.mState.getReportedProcState());
  43. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
  44. "Process cur broadcast " + r + " DELIVERED for app " + app);
  45. started = true;
  46. } finally {
  47. if (!started) {
  48. //若启动失败,则打印对应的信息
  49. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
  50. "Process cur broadcast " + r + ": NOT STARTED!");
  51. r.receiver = null;
  52. r.curApp = null;
  53. prr.removeCurReceiver(r);
  54. }
  55. }
  56. }

APP存在,调用ApplicationThread的scheduleReceiver方法

android/frameworks/base/core/java/android/app/ActivityThread.java
  1. private class ApplicationThread extends IApplicationThread.Stub {
  2. private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
  3. public final void scheduleReceiver(Intent intent, ActivityInfo info,
  4. CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
  5. boolean sync, int sendingUser, int processState) {
  6. updateProcessState(processState, false);
  7. ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
  8. sync, false, mAppThread.asBinder(), sendingUser);
  9. r.info = info;
  10. r.compatInfo = compatInfo;
  11. sendMessage(H.RECEIVER, r);
  12. }
  13. public void handleMessage(Message msg) {
  14. if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
  15. case RECEIVER:
  16. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
  17. //使用handleReceiver函数
  18. handleReceiver((ReceiverData)msg.obj);
  19. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

APP存在,调用ApplicationThread的handleReceiver方法

  1. @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
  2. private void handleReceiver(ReceiverData data) {
  3. // If we are getting ready to gc after going to the background, well
  4. // we are back active so skip it.
  5. unscheduleGcIdler();
  6. // 1) 创建BroadcastReceiver对象
  7. // 这里处理的是静态广播接收者,默认认为接收者BroadcastReceiver对象不存在
  8. // 每次接受都会创建一个新的BroadcastReceiver对象
  9. //获取组件
  10. String component = data.intent.getComponent().getClassName();
  11. //获取packageinfo 对象
  12. LoadedApk packageInfo = getPackageInfoNoCheck(
  13. data.info.applicationInfo, data.compatInfo);
  14. IActivityManager mgr = ActivityManager.getService();
  15. Application app;
  16. BroadcastReceiver receiver;
  17. ContextImpl context;
  18. try {
  19. // 首先从AMS传递的intent中获取当前处理该广播的组件名称,然后通过反射创建一个BroadcastReceiver
  20. // 对象,从这里可以看出来,静态广播处理的时候,每次都会创建一个新的BroadcastReceiver对象;
  21. // 创建Application对象,如果进程已经启动,Application对象已经创建
  22. app = packageInfo.makeApplication(false, mInstrumentation);
  23. context = (ContextImpl) app.getBaseContext();
  24. if (data.info.splitName != null) {
  25. context = (ContextImpl) context.createContextForSplit(data.info.splitName);
  26. }
  27. if (data.info.attributionTags != null && data.info.attributionTags.length > 0) {
  28. final String attributionTag = data.info.attributionTags[0];
  29. context = (ContextImpl) context.createAttributionContext(attributionTag);
  30. }
  31. java.lang.ClassLoader cl = context.getClassLoader();
  32. data.intent.setExtrasClassLoader(cl);
  33. data.intent.prepareToEnterProcess(
  34. isProtectedComponent(data.info) || isProtectedBroadcast(data.intent),
  35. context.getAttributionSource());
  36. data.setExtrasClassLoader(cl);
  37. receiver = packageInfo.getAppFactory()
  38. .instantiateReceiver(cl, data.info.name, data.intent);
  39. } catch (Exception e) {
  40. if (DEBUG_BROADCAST) Slog.i(TAG,
  41. "Finishing failed broadcast to " + data.intent.getComponent());
  42. data.sendFinished(mgr);
  43. throw new RuntimeException(
  44. "Unable to instantiate receiver " + component
  45. + ": " + e.toString(), e);
  46. }
  47. // 2) 执行onReceive函数
  48. try {
  49. if (localLOGV) Slog.v(
  50. TAG, "Performing receive of " + data.intent
  51. + ": app=" + app
  52. + ", appName=" + app.getPackageName()
  53. + ", pkg=" + packageInfo.getPackageName()
  54. + ", comp=" + data.intent.getComponent().toShortString()
  55. + ", dir=" + packageInfo.getAppDir());
  56. sCurrentBroadcastIntent.set(data.intent);
  57. // 调用接收者的onReceive方法,这里还调用了setPendingResult方法,详细内容请看BroadcastReceiver.goAsync方法。
  58. receiver.setPendingResult(data);
  59. receiver.onReceive(context.getReceiverRestrictedContext(),
  60. data.intent);
  61. } catch (Exception e) {
  62. if (DEBUG_BROADCAST) Slog.i(TAG,
  63. "Finishing failed broadcast to " + data.intent.getComponent());
  64. data.sendFinished(mgr);
  65. if (!mInstrumentation.onException(receiver, e)) {
  66. throw new RuntimeException(
  67. "Unable to start receiver " + component
  68. + ": " + e.toString(), e);
  69. }
  70. } finally {
  71. sCurrentBroadcastIntent.set(null);
  72. }
  73. if (receiver.getPendingResult() != null) {
  74. // 3) 向AMS发送处理结束消息
  75. data.finish();
  76. }
  77. }

上面代码主要干了三件事情:

  • 创建BroadcastReceiver对象;
  • 执行onReceive函数;
  • AMS发送处理结束消息,通知将当前广播发送给下一个接收者;

APP未启动,先创建该进程
如果静态广播接收者进程尚未启动,会直接调用AMS的startProcessLocked函数启动该接收者进程,并将当前正在等待进程
启动的BroadcastRecord存储到mPendingBroadcast里面,这个就是静态广播拉起应用的原理。

在app进程启动之后,会先调用applicationattachonCreate方法,然后才会调用ActivityManagerServicesendPendingBroadcastsLocked方法。
 

  1. // The app just attached; send any pending broadcasts that it should receive
  2. boolean sendPendingBroadcastsLocked(ProcessRecord app) {
  3. boolean didSomething = false;
  4. for (BroadcastQueue queue : mBroadcastQueues) {
  5. //调用BroadcastQueue的sendPendingBroadcastsLocked方法
  6. didSomething |= queue.sendPendingBroadcastsLocked(app);
  7. }
  8. return didSomething;
  9. }

mBroadcastQueues是包含前台和后台广播队列,这里分别调用前台和后台优先级广播的BroadcastQueue.sendPendingBroadcastsLocked方法。

调用BroadcastQueue的sendPendingBroadcastsLocked方法

  1. // 未启动进程的广播接收者需要先启动进程,最后到达这个函数
  2. public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
  3. boolean didSomething = false;
  4. final BroadcastRecord br = mPendingBroadcast;
  5. if (br != null && br.curApp.getPid() > 0 && br.curApp.getPid() == app.getPid()) {
  6. if (br.curApp != app) {
  7. Slog.e(TAG, "App mismatch when sending pending broadcast to "
  8. + app.processName + ", intended target is " + br.curApp.processName);
  9. return false;
  10. }
  11. try {
  12. //启动完成设置为null
  13. mPendingBroadcast = null;
  14. //调用processCurBroadcastLocked方法进行处理
  15. processCurBroadcastLocked(br, app);
  16. didSomething = true;
  17. } catch (Exception e) {
  18. Slog.w(TAG, "Exception in new application when starting receiver "
  19. + br.curComponent.flattenToShortString(), e);
  20. logBroadcastReceiverDiscardLocked(br);
  21. finishReceiverLocked(br, br.resultCode, br.resultData,
  22. br.resultExtras, br.resultAbort, false);
  23. scheduleBroadcastsLocked();
  24. // We need to reset the state if we failed to start the receiver.
  25. br.state = BroadcastRecord.IDLE;
  26. throw new RuntimeException(e.getMessage());
  27. }
  28. }
  29. return didSomething;
  30. }

这里是找到等待处理的广播并且判断是否为空,以及是否和当前进程的pid相同,也就是不是这个进程的等待广播,如果是就调用processCurBroadcastLocked方法进行处理,后面的处理和上面app已启动的流程一致了。

5、流程总结

上面流程大体流程图:

执行时序图:

三、总结
看完源码再来看下一开始的问题:
1、广播为啥会阻塞呢?发送给接收器就行了,为啥还要等着接收器处理完才处理下一个?

从上面的源码分析可知,广播的处理分为并行和有序两个队列,出问题的无序广播静态接收器放在了有序处理列表中,而有序处理列表的执行是串行的,只有前面的执行完,才会轮到下一个处理,所以前面的广播如果在onReceive中有耗时操作,后面的广播就会堵塞。

2、 由普通的后台广播改为前台广播后,为啥处理的会更快?

在上面源码中有个变量的注释:mTimeoutPeriod。这个变量初始化是在BroadcastQueue初始化的时候传入的,也就是在AMS(AMS构造函数中)中初始化mFgBroadcastQueuemBgBroadcastQueue时传入的,前台广播的超时时间是10s,后台的超时时间是60s。 也会出现一种问题,就是产生发生ANR的时间段时间不一样.
 

BROADCAST_FG_TIMEOUT = 10 * 1000 
BROADCAST_BG_TIMEOUT = 60 * 1000

后台广播的设计思想就是当前应用优先,尽可能多让收到广播的应用有充足的时间把事件做完

而前台广播的目的是紧急通知,设计上就倾向于当前应用赶快处理完,尽快传给下一个

也就是说在设计上前台广播主要用于响应性能较高的场景,因为ANR时间是10s,所以开发设计的时候应该尽可能少用。因为前台广播使用的比较少,所以队列相对空闲,响应速度快。

3、对照源码分析总结:

    (1) 前后台队列都有自己并行和有序广播队列,互相不影响;
    (2) 并行队列里是无序广播+动态注册接收者;
    (3) 有序队列里是有序广播+动态接收者和静态接收者,静态接收者默认就是有序的;
    (4) 有序广播+动态接收者执行优于静态接收者先执行,综合起来就是广播相同的情况下,动态接收器优于静态接收器;
    (5) Android版本高的,很多系统广播只支持动态注册,静态注册的话收不到广播,例如:息屏亮屏广播。因为静态注册的话,发广播的时候会把所有注册未启动的app全部拉起来,静态处理器默认串行处理,增加了广播的处理时间。
 

知识点介绍:

1. instant app :谷歌推出的类似于微信小程序(或者说小程序类似于instant app)的一项技术,用户无须安装应用,用完就走,同时兼备h5的便捷和原生应用的优质体验。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/308540
推荐阅读
相关标签
  

闽ICP备14008679号