当前位置:   article > 正文

Android 中broadcast 发送过程解析

Android 中broadcast 发送过程解析

请支持原创~~

 

相关博文:

Android基础总结之五:BroadcastReceiver

Android 中broadcast 注册过程解析

Android 中broadcast 发送过程解析

protected-broadcast 规范使用(ERROR: Sending non-protected broadcast)

 

 

基于版本:Android O

0. 前言

上一篇博文 Android 中broadcast 注册过程解析 详细的解析了广播的注册过程,最终AMS 端的mRegisteredReceivers 保存了所有的动态注册进来的广播,并且一一对应ReceiverDispatcher。这一篇接着解析广播的另一半功能——发送过程。

1. context.sendBroadcast()

用户可以通过context 的接口进行广播的发布,系统会对其进行进一步的通知。接口比较多,如下:

  1. public void sendBroadcast(Intent intent)
  2. public void sendBroadcast(Intent intent, int userId)
  3. public void sendBroadcast(Intent intent, String receiverPermission)
  4. public void sendOrderedBroadcast(Intent intent, String receiverPermission)
  5. public void sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)
  6. public void sendStickyBroadcast(Intent intent)
  7. public void sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)

其中sendBroadcast()是最简单的发送广播的动作。而sendOrderedBroadcast(),则是用来向系统发出有序广播(Ordered broadcast)的。这种有序广播对应的所有接收器只能按照一定的优先级顺序,依次接收intent。这些优先级一般记录在AndroidManifest.xml文件中,具体位置在<intent-filter>元素的android:priority属性中,其数值越大表示优先级越高,取值范围为-1000到1000。另外,有时候我们也可以调用IntentFilter对象的setPriority()方法来设置优先级。

对于有序广播而言,前面的接收者可以对接收到的广播intent进行处理,并将处理结果放置到广播intent中,然后传递给下一个接收者。需要注意的是,前面的接收者有权终止广播的进一步传播。也就是说,如果广播被前面的接收者终止了,那么后面的接收器就再也无法接收到广播了。

还有一个怪东西,叫做sticky广播,它又是什么呢?简单地说,sticky广播可以保证“在广播递送时尚未注册的receiver”,一旦日后注册进系统,就能够马上接到“错过”的sticky广播。在上一篇博文 Android 中broadcast 注册过程解析  中已经详细的分析了sticky 广播在注册的时候执行流程。

下面我们挑其中比较经典常用的接口来解释:

  1. @Override
  2. public void sendBroadcast(Intent intent, String receiverPermission) {
  3. warnIfCallingFromSystemProcess();
  4. String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
  5. String[] receiverPermissions = receiverPermission == null ? null
  6. : new String[] {receiverPermission};
  7. try {
  8. intent.prepareToLeaveProcess(this);
  9. ActivityManager.getService().broadcastIntent(
  10. mMainThread.getApplicationThread(), intent, resolvedType, null,
  11. Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
  12. null, false, false, getUserId());
  13. } catch (RemoteException e) {
  14. throw e.rethrowFromSystemServer();
  15. }
  16. }

将广播的intent 和receiver 想要接受此广播务必需要的权限,当然这个权限也可以为null,代表不收权限的限制。

最终会调用到AMS 中的broadcastIntent 接口,注意函数中传入的参数:

  • 第1个参数是发送端的appThread
  • 第2个参数是广播的intent
  • 第5个参数是resultCode
  • 第8个参数是receiver 所需要的权限
  • 第9个参数是AppOps所需要的op 码
  • 第10个参数是广播所携带的参数,Bundle形式
  • 最后一个参数是user id(跟uid 不一样)

2. AMS.broadcastIntent()

  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 bOptions,
  5. boolean serialized, boolean sticky, int userId) {
  6. enforceNotIsolatedCaller("broadcastIntent");
  7. synchronized(this) {
  8. intent = verifyBroadcastLocked(intent);
  9. final ProcessRecord callerApp = getRecordForAppLocked(caller); //传过来的thread会变成ProcessRecord
  10. final int callingPid = Binder.getCallingPid(); //发送端的 pid
  11. final int callingUid = Binder.getCallingUid(); //发送端的 uid
  12. final long origId = Binder.clearCallingIdentity();
  13. int res = broadcastIntentLocked(callerApp,
  14. callerApp != null ? callerApp.info.packageName : null,
  15. intent, resolvedType, resultTo, resultCode, resultData, resultExtras,
  16. requiredPermissions, appOp, bOptions, serialized, sticky,
  17. callingPid, callingUid, userId);
  18. Binder.restoreCallingIdentity(origId);
  19. return res;
  20. }
  21. }

同样最终会调用到broadcastIntentLocked,注意函数中传入的参数:

  • 第1个参数为callerApp,发送端的ProcessRecord
  • 第2个参数是发送端的 packageName
  • 第3个参数是最开始传过来的广播的intent
  • 第9个参数是接收端需要接收广播所需的permission
  • 第10个参数是AppOps 所需要的op 码
  • 最后几个参数是call 端的pid、uid和 user id。

3. AMS.broadcastIntentLocked()

由于代码比较长,这里分段来解读。

3.1 当广播有参数的时候,确认权限

  1. BroadcastOptions brOptions = null;
  2. if (bOptions != null) {
  3. brOptions = new BroadcastOptions(bOptions);
  4. if (brOptions.getTemporaryAppWhitelistDuration() > 0) {
  5. // See if the caller is allowed to do this. Note we are checking against
  6. // the actual real caller (not whoever provided the operation as say a
  7. // PendingIntent), because that who is actually supplied the arguments.
  8. if (checkComponentPermission(
  9. android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
  10. Binder.getCallingPid(), Binder.getCallingUid(), -1, true)
  11. != PackageManager.PERMISSION_GRANTED) {
  12. String msg = "Permission Denial: " + intent.getAction()
  13. + " broadcast from " + callerPackage + " (pid=" + callingPid
  14. + ", uid=" + callingUid + ")"
  15. + " requires "
  16. + android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST;
  17. Slog.w(TAG, msg);
  18. throw new SecurityException(msg);
  19. }
  20. }
  21. }

这里的BroadcastOptions 就是处理第一步中第10个参数,一般没有的话为null。

  1. public BroadcastOptions(Bundle opts) {
  2. mTemporaryAppWhitelistDuration = opts.getLong(KEY_TEMPORARY_APP_WHITELIST_DURATION);
  3. mMinManifestReceiverApiLevel = opts.getInt(KEY_MIN_MANIFEST_RECEIVER_API_LEVEL, 0);
  4. mMaxManifestReceiverApiLevel = opts.getInt(KEY_MAX_MANIFEST_RECEIVER_API_LEVEL,
  5. Build.VERSION_CODES.CUR_DEVELOPMENT);
  6. }

3.2 确认广播为protected 广播,而只有system code 才能发送protected 广播

  1. // Verify that protected broadcasts are only being sent by system code,
  2. // and that system code is only sending protected broadcasts.
  3. final String action = intent.getAction();
  4. final boolean isProtectedBroadcast;
  5. try {
  6. isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action);
  7. } catch (RemoteException e) {
  8. Slog.w(TAG, "Remote exception", e);
  9. return ActivityManager.BROADCAST_SUCCESS;
  10. }
  11. final boolean isCallerSystem;
  12. switch (UserHandle.getAppId(callingUid)) {
  13. case ROOT_UID:
  14. case SYSTEM_UID:
  15. case PHONE_UID:
  16. case BLUETOOTH_UID:
  17. case NFC_UID:
  18. isCallerSystem = true;
  19. break;
  20. default:
  21. isCallerSystem = (callerApp != null) && callerApp.persistent;
  22. break;
  23. }
  24. // First line security check before anything else: stop non-system apps from
  25. // sending protected broadcasts.
  26. if (!isCallerSystem) {
  27. if (isProtectedBroadcast) {//非system code 不能发送protected 广播
  28. String msg = "Permission Denial: not allowed to send broadcast "
  29. + action + " from pid="
  30. + callingPid + ", uid=" + callingUid;
  31. Slog.w(TAG, msg);
  32. throw new SecurityException(msg);
  33. } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
  34. || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
  35. // Special case for compatibility: we don't want apps to send this,
  36. // but historically it has not been protected and apps may be using it
  37. // to poke their own app widget. So, instead of making it protected,
  38. // just limit it to the caller.
  39. if (callerPackage == null) {
  40. String msg = "Permission Denial: not allowed to send broadcast "
  41. + action + " from unknown caller.";
  42. Slog.w(TAG, msg);
  43. throw new SecurityException(msg);
  44. } else if (intent.getComponent() != null) {
  45. // They are good enough to send to an explicit component... verify
  46. // it is being sent to the calling app.
  47. if (!intent.getComponent().getPackageName().equals(
  48. callerPackage)) {
  49. String msg = "Permission Denial: not allowed to send broadcast "
  50. + action + " to "
  51. + intent.getComponent().getPackageName() + " from "
  52. + callerPackage;
  53. Slog.w(TAG, msg);
  54. throw new SecurityException(msg);
  55. }
  56. } else {
  57. // Limit broadcast to their own package.
  58. intent.setPackage(callerPackage);
  59. }
  60. }
  61. }

这一段要求,如果是protected broadcast,那么只能system uid 才能发送,对于非system uid 的app 不能发送protected broadcast。对于protected broadcast 的具体使用规范,可以看下:

protected-broadcast 规范使用(ERROR: Sending non-protected broadcast)

3.3 处理Package 相关的广播

这部分的code 比较多,这里不全部贴出来,主要是package 相关的广播,还有time、timezone 等广播,如下:

  1. case Intent.ACTION_UID_REMOVED:
  2. case Intent.ACTION_PACKAGE_REMOVED:
  3. case Intent.ACTION_PACKAGE_CHANGED:
  4. case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
  5. case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
  6. case Intent.ACTION_PACKAGES_SUSPENDED:
  7. case Intent.ACTION_PACKAGES_UNSUSPENDED:
  8. case Intent.ACTION_PACKAGE_REPLACED:
  9. case Intent.ACTION_PACKAGE_ADDED:
  10. case Intent.ACTION_PACKAGE_DATA_CLEARED:
  11. case Intent.ACTION_TIMEZONE_CHANGED:
  12. case Intent.ACTION_TIME_CHANGED:
  13. case Intent.ACTION_CLEAR_DNS_CACHE:
  14. case Proxy.PROXY_CHANGE_ACTION:
  15. case android.hardware.Camera.ACTION_NEW_PICTURE:
  16. case android.hardware.Camera.ACTION_NEW_VIDEO:

3.4 如果是sticky 广播,添加到mStickyBroadcasts 列表中

mStickyBroadcasts.put(userId, stickies);

其中根据参数sticky 来确定发送的时候为sticky 广播,如果是会添加到mStickyBroadcasts 列表中。

Android 中broadcast 注册过程解析 我们也看到注册进来的广播也会先确认是否在mStickyBroadcasts 中是否存在。

3.5 尝试向并行receivers递送广播

  1. // Figure out who all will receive this broadcast.
  2. List receivers = null;
  3. List<BroadcastFilter> registeredReceivers = null;
  4. // Need to resolve the intent to interested receivers...
  5. if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
  6. == 0) {
  7. // 收集注册的 receiver,这个应该是静态的广播
  8. receivers = collectReceiverComponents(intent, resolvedType, callingUid, users);
  9. }
  10. if (intent.getComponent() == null) {
  11. if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) {
  12. // Query one target user at a time, excluding shell-restricted users
  13. for (int i = 0; i < users.length; i++) {
  14. if (mUserController.hasUserRestriction(
  15. UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) {
  16. continue;
  17. }
  18. List<BroadcastFilter> registeredReceiversForUser =
  19. mReceiverResolver.queryIntent(intent,
  20. resolvedType, false /*defaultOnly*/, users[i]);
  21. if (registeredReceivers == null) {
  22. registeredReceivers = registeredReceiversForUser;
  23. } else if (registeredReceiversForUser != null) {
  24. registeredReceivers.addAll(registeredReceiversForUser);
  25. }
  26. }
  27. } else {
  28. // 获取动态注册的广播
  29. registeredReceivers = mReceiverResolver.queryIntent(intent,
  30. resolvedType, false /*defaultOnly*/, userId);
  31. }
  32. }
  33. final boolean replacePending =
  34. (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
  35. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction()
  36. + " replacePending=" + replacePending);
  37. int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
  38. // 这个判断很重要
  39. if (!ordered && NR > 0) {
  40. // If we are not serializing this broadcast, then send the
  41. // registered receivers separately so they don't wait for the
  42. // components to be launched.
  43. if (isCallerSystem) {
  44. checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
  45. isProtectedBroadcast, registeredReceivers);
  46. }
  47. final BroadcastQueue queue = broadcastQueueForIntent(intent);
  48. BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
  49. callerPackage, callingPid, callingUid, callerInstantApp, resolvedType,
  50. requiredPermissions, appOp, brOptions, registeredReceivers, resultTo,
  51. resultCode, resultData, resultExtras, ordered, sticky, false, userId);
  52. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r);
  53. final boolean replaced = replacePending
  54. && (queue.replaceParallelBroadcastLocked(r) != null);
  55. // Note: We assume resultTo is null for non-ordered broadcasts.
  56. if (!replaced) {
  57. // 添加到并行广播列表中
  58. queue.enqueueParallelBroadcastLocked(r);
  59. // 开始分发广播
  60. queue.scheduleBroadcastsLocked();
  61. }
  62. registeredReceivers = null;
  63. NR = 0;
  64. }

这段code 其实获取了两种广播:

  • 通过collectReceiverComponents() 函数获取静态注册的广播
  • 通过mReceiverResolver.queryIntent() 函数获取了动态注册的广播

其中有个判断很重要:

  1. int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
  2. if (!ordered && NR > 0) {

如果存在动态注册的广播,如果没有声明进行有序分发广播,就不会将这里的动态注册广播添加到静态注册的广播list 中。下面会解释。

 如果没有声明是有序分发广播,这里的动态注册广播会以并行广播进行分发(详见scheduleBroadcastsLocked())。

另外,这里会new一个BroadcastRecord节点,并插入BroadcastQueue内的并行处理队列,最后发起实际的广播调度(scheduleBroadcastsLocked())。

其实不光并行处理部分需要一个BroadcastRecord节点,串行处理部分也需要BroadcastRecord节点。也就是说,要激发一次广播,AMS必须构造一个或两个BroadcastRecord节点,并将之插入合适的广播队列(mFgBroadcastQueue或mBgBroadcastQueue)。插入成功后,再执行队列的scheduleBroadcastsLocked()动作,进行实际的派发调度。

如果不是有序广播,最后会在并行分发完成之后重置:

  1. registeredReceivers = null;
  2. NR = 0;

这一部分的code 暂时先解析到这里,其中关键的分发函数scheduleBroadcastsLocked() 后面会解析。

3.6 尝试逐个向串行receivers递送广播

  1. // Merge into one list.
  2. int ir = 0;
  3. if (receivers != null) {
  4. ...
  5. ...
  6. int NT = receivers != null ? receivers.size() : 0;
  7. int it = 0;
  8. ResolveInfo curt = null;
  9. BroadcastFilter curr = null;
  10. while (it < NT && ir < NR) {
  11. if (curt == null) {
  12. curt = (ResolveInfo)receivers.get(it);
  13. }
  14. if (curr == null) {
  15. curr = registeredReceivers.get(ir);
  16. }
  17. if (curr.getPriority() >= curt.priority) {
  18. // Insert this broadcast record into the final list.
  19. receivers.add(it, curr);
  20. ir++;
  21. curr = null;
  22. it++;
  23. NT++;
  24. } else {
  25. // Skip to the next ResolveInfo in the final list.
  26. it++;
  27. curt = null;
  28. }
  29. }
  30. }
  31. while (ir < NR) {
  32. if (receivers == null) {
  33. receivers = new ArrayList();
  34. }
  35. receivers.add(registeredReceivers.get(ir));
  36. ir++;
  37. }

首先来看下这段code,上面3.5 中说到如果是有序广播,动态注册的广播并不会立刻分发,而是会到这里跟这里receivers list进行有效的合并。

下面来看receivers 进行有序分发:

  1. if ((receivers != null && receivers.size() > 0)
  2. || resultTo != null) {
  3. BroadcastQueue queue = broadcastQueueForIntent(intent);
  4. BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
  5. callerPackage, callingPid, callingUid, callerInstantApp, resolvedType,
  6. requiredPermissions, appOp, brOptions, receivers, resultTo, resultCode,
  7. resultData, resultExtras, ordered, sticky, false, userId);
  8. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r
  9. + ": prev had " + queue.mOrderedBroadcasts.size());
  10. if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
  11. "Enqueueing broadcast " + r.intent.getAction());
  12. final BroadcastRecord oldRecord =
  13. replacePending ? queue.replaceOrderedBroadcastLocked(r) : null;
  14. if (oldRecord != null) {
  15. // Replaced, fire the result-to receiver.
  16. if (oldRecord.resultTo != null) {
  17. final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent);
  18. try {
  19. oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo,
  20. oldRecord.intent,
  21. Activity.RESULT_CANCELED, null, null,
  22. false, false, oldRecord.userId);
  23. } catch (RemoteException e) {
  24. Slog.w(TAG, "Failure ["
  25. + queue.mQueueName + "] sending broadcast result of "
  26. + intent, e);
  27. }
  28. }
  29. } else {
  30. // 将BroadcastRecord 添加到串行广播列表中
  31. queue.enqueueOrderedBroadcastLocked(r);
  32. // 进行最后的分发工作
  33. queue.scheduleBroadcastsLocked();
  34. }
  35. }

3.7 广播的递送

  1. public void scheduleBroadcastsLocked() {
  2. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
  3. + mQueueName + "]: current="
  4. + mBroadcastsScheduled);
  5. if (mBroadcastsScheduled) {
  6. return;
  7. }
  8. mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
  9. mBroadcastsScheduled = true;
  10. }

进行了异步操作,如果这个分发的指令刚发送完,下一次再来会直接return,最终会调用 processNextBroadcast() 这也是分发的核心所在。

4. BroadcastQueue.processNextBroadcast()

这个函数是广播分发的核心所在,代码比较长,我们还是分段进行解析。

4.1 重置mBroadcastsScheduled

  1. if (fromMsg) {
  2. mBroadcastsScheduled = false;
  3. }

将mBroadcastsScheduled设为false是让下一条消息能发送。

4.2 立刻解析并行广播

  1. // First, deliver any non-serialized broadcasts right away.
  2. while (mParallelBroadcasts.size() > 0) {
  3. r = mParallelBroadcasts.remove(0);
  4. r.dispatchTime = SystemClock.uptimeMillis();
  5. r.dispatchClockTime = System.currentTimeMillis();
  6. final int N = r.receivers.size();
  7. for (int i=0; i<N; i++) {
  8. Object target = r.receivers.get(i);
  9. deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
  10. }
  11. addBroadcastToHistoryLocked(r);
  12. }

mParallelBroadcasts 上面我们在broadcastIntentLocked() 的时候说过,不管是fg 还是bg 最终的BroadRecord 都会保存在这里。

并行广播其实说法有点片面,称无序广播更好,因为这里map 排列的时候是没有顺序的 ,但是发布的时候还是要从第一个广播开始匹配。

详细deliverToRegisteredReceiverLocked() 函数看下面第5 点。

4.3 处理串行广播

在处理串行广播之前有一段code:

  1. if (mPendingBroadcast != null) {
  2. if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
  3. "processNextBroadcast [" + mQueueName + "]: waiting for "
  4. + mPendingBroadcast.curApp);
  5. boolean isDead;
  6. synchronized (mService.mPidsSelfLocked) {
  7. ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
  8. isDead = proc == null || proc.crashing;
  9. }
  10. if (!isDead) {
  11. // It's still alive, so keep waiting
  12. return;
  13. } else {
  14. Slog.w(TAG, "pending app ["
  15. + mQueueName + "]" + mPendingBroadcast.curApp
  16. + " died before responding to broadcast");
  17. mPendingBroadcast.state = BroadcastRecord.IDLE;
  18. mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
  19. mPendingBroadcast = null;
  20. }
  21. }

最开始发广播的时候可能程序并没有起来,mPendingBroadcast 保存的是上一次分发给应用还没有start 的广播。详细看下面4.6 节。

  1. do {
  2. if (mOrderedBroadcasts.size() == 0) {
  3. // 最后一条广播处理会gc 一下
  4. mService.scheduleAppGcsLocked();
  5. if (looped) {
  6. // 最后一条处理会更新所有进程oom
  7. mService.updateOomAdjLocked();
  8. }
  9. return;
  10. }
  11. // 如果有序广播还有,get 第一个开始处理
  12. r = mOrderedBroadcasts.get(0);
  13. boolean forceReceive = false;
  14. // 这里处理广播的ANR
  15. int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
  16. if (mService.mProcessesReady && r.dispatchTime > 0) {
  17. long now = SystemClock.uptimeMillis();
  18. if ((numReceivers > 0) &&
  19. (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
  20. // 注意这里的这个函数
  21. broadcastTimeoutLocked(false); // forcibly finish this broadcast
  22. forceReceive = true;
  23. r.state = BroadcastRecord.IDLE;
  24. }
  25. }
  26. ...
  27. if (r.receivers == null || r.nextReceiver >= numReceivers
  28. || r.resultAbort || forceReceive) {
  29. // No more receivers for this broadcast! Send the final
  30. // result if requested...
  31. if (r.resultTo != null) {
  32. try {
  33. //处理广播消息消息,调用到onReceive()
  34. performReceiveLocked(r.callerApp, r.resultTo,
  35. new Intent(r.intent), r.resultCode,
  36. r.resultData, r.resultExtras, false, false, r.userId);
  37. r.resultTo = null;
  38. } catch (RemoteException e) {
  39. r.resultTo = null;
  40. Slog.w(TAG, "Failure ["
  41. + mQueueName + "] sending broadcast result of "
  42. + r.intent, e);
  43. }
  44. }
  45. //取消BROADCAST_TIMEOUT_MSG消息
  46. cancelBroadcastTimeoutLocked();
  47. if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
  48. "Finished with ordered broadcast " + r);
  49. // ... and on to the next...
  50. addBroadcastToHistoryLocked(r);
  51. mOrderedBroadcasts.remove(0);
  52. r = null;
  53. looped = true;
  54. continue;
  55. }
  56. } while (r == null);

mTimeoutPeriod,对于前台广播则为10s,对于后台广播则为60s。广播超时为2*mTimeoutPeriod*numReceivers,接收者个数numReceivers越多则广播超时总时长越大。

4.4 处理动态注册的有序广播

  1. final Object nextReceiver = r.receivers.get(recIdx);
  2. if (nextReceiver instanceof BroadcastFilter) {
  3. // Simple case: this is a registered receiver who gets
  4. // a direct call.
  5. BroadcastFilter filter = (BroadcastFilter)nextReceiver;
  6. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
  7. "Delivering ordered ["
  8. + mQueueName + "] to registered "
  9. + filter + ": " + r);
  10. deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
  11. if (r.receiver == null || !r.ordered) {
  12. // The receiver has already finished, so schedule to
  13. // process the next one.
  14. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
  15. + mQueueName + "]: ordered="
  16. + r.ordered + " receiver=" + r.receiver);
  17. r.state = BroadcastRecord.IDLE;
  18. scheduleBroadcastsLocked();
  19. } else {
  20. if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
  21. scheduleTempWhitelistLocked(filter.owningUid,
  22. brOptions.getTemporaryAppWhitelistDuration(), r);
  23. }
  24. }
  25. return;
  26. }

之前在 3.2 节中讲过,对于动态注册的广播首先确定是否是以有序广播的形式发出,如果是以有序广播的形式,最后不会调用deliverToRegisteredReceiverLocked() 函数,而是添加到receivers 列表中。这里可以看到,动态注册的广播最终还是会通过deliverToRegisteredReceiverLocked() 函数进行分发。详细看下面的第 5节。

4.5 处理静态注册的有序广播

这段code 太长,暂时不贴出来了,最开始的时候会进行权限的check,跟下面第 5 节分发并行广播差不多。

其中有意思的一段:

  1. if (!skip) {
  2. skip = !mService.isAutoStartAllowed(info.activityInfo.applicationInfo.uid, info.activityInfo.applicationInfo.packageName);
  3. }

AMS 中对于应用有这样一个自启动功能的验证。(我之前做自启动管理的时候并没有发现还有这个,失败~~)

继续顺着code 往下解读,最终发现有序广播的处理code:

  1. // Is this receiver's application already running?
  2. if (app != null && app.thread != null && !app.killed) {
  3. try {
  4. app.addPackage(info.activityInfo.packageName,
  5. info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
  6. processCurBroadcastLocked(r, app);
  7. return;
  8. } catch (RemoteException e) {
  9. Slog.w(TAG, "Exception when sending broadcast to "
  10. + r.curComponent, e);
  11. } catch (RuntimeException e) {
  12. Slog.wtf(TAG, "Failed sending broadcast to "
  13. + r.curComponent + " with " + r.intent, e);
  14. // If some unexpected exception happened, just skip
  15. // this broadcast. At this point we are not in the call
  16. // from a client, so throwing an exception out from here
  17. // will crash the entire system instead of just whoever
  18. // sent the broadcast.
  19. logBroadcastReceiverDiscardLocked(r);
  20. finishReceiverLocked(r, r.resultCode, r.resultData,
  21. r.resultExtras, r.resultAbort, false);
  22. scheduleBroadcastsLocked();
  23. // We need to reset the state if we failed to start the receiver.
  24. r.state = BroadcastRecord.IDLE;
  25. return;
  26. }
  27. // If a dead object exception was thrown -- fall through to
  28. // restart the application.
  29. }

注意,这段code 条件指的是应用已经运行。终于找到了有序广播的分发接口processCurBroadcastLocked()。

当程序没有运行的时候会执行下面这段code:

  1. if ((r.curApp=mService.startProcessLocked(targetProcess,
  2. info.activityInfo.applicationInfo, true,
  3. r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
  4. "broadcast", r.curComponent,
  5. (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
  6. == null) {
  7. // Ah, this recipient is unavailable. Finish it if necessary,
  8. // and mark the broadcast record as ready for the next.
  9. Slog.w(TAG, "Unable to launch app "
  10. + info.activityInfo.applicationInfo.packageName + "/"
  11. + info.activityInfo.applicationInfo.uid + " for broadcast "
  12. + r.intent + ": process is bad");
  13. logBroadcastReceiverDiscardLocked(r);
  14. finishReceiverLocked(r, r.resultCode, r.resultData,
  15. r.resultExtras, r.resultAbort, false);
  16. scheduleBroadcastsLocked();
  17. r.state = BroadcastRecord.IDLE;
  18. return;
  19. }

直接finishReceiverLocked(),并继续执行scheduleBroadcastsLocked() 开始下一条广播分发。

4.6 广播没发出去,继续下一轮分发

  1. mPendingBroadcast = r;
  2. mPendingBroadcastRecvIndex = recIdx;

如果程序启动成功的话,会将广播pending,记录一下为了下一次的优先分发。

5. deliverToRegisteredReceiverLocked()

函数比较长,继续分段来解读。

5.1 check 发送端是否拥有接收端要求的权限

  1. if (filter.requiredPermission != null) {
  2. int perm = mService.checkComponentPermission(filter.requiredPermission,
  3. r.callingPid, r.callingUid, -1, true);
  4. if (perm != PackageManager.PERMISSION_GRANTED) {
  5. Slog.w(TAG, "Permission Denial: broadcasting "
  6. + r.intent.toString()
  7. + " from " + r.callerPackage + " (pid="
  8. + r.callingPid + ", uid=" + r.callingUid + ")"
  9. + " requires " + filter.requiredPermission
  10. + " due to registered receiver " + filter);
  11. skip = true;
  12. } else {
  13. final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
  14. if (opCode != AppOpsManager.OP_NONE
  15. && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
  16. r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
  17. Slog.w(TAG, "Appop Denial: broadcasting "
  18. + r.intent.toString()
  19. + " from " + r.callerPackage + " (pid="
  20. + r.callingPid + ", uid=" + r.callingUid + ")"
  21. + " requires appop " + AppOpsManager.permissionToOp(
  22. filter.requiredPermission)
  23. + " due to registered receiver " + filter);
  24. skip = true;
  25. }
  26. }
  27. }

Android 中broadcast 注册过程解析 一文中我们说到register 广播的接口比较多,其中有一个带权限的。这个就要求发送端需要具备这个权限。系统中确认这个权限的时候有两种方式,一个是通过PMS 中的runtime permission,另一个是通过AppOps的正常权限。

如果这里没有给出规定的权限,这个广播是无法发布出去的。

  1. if (skip) {
  2. r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
  3. return;
  4. }

5.2 check 接收端是否拥有发送端要求的权限

  1. if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
  2. for (int i = 0; i < r.requiredPermissions.length; i++) {
  3. String requiredPermission = r.requiredPermissions[i];
  4. int perm = mService.checkComponentPermission(requiredPermission,
  5. filter.receiverList.pid, filter.receiverList.uid, -1, true);
  6. if (perm != PackageManager.PERMISSION_GRANTED) {
  7. Slog.w(TAG, "Permission Denial: receiving "
  8. + r.intent.toString()
  9. + " to " + filter.receiverList.app
  10. + " (pid=" + filter.receiverList.pid
  11. + ", uid=" + filter.receiverList.uid + ")"
  12. + " requires " + requiredPermission
  13. + " due to sender " + r.callerPackage
  14. + " (uid " + r.callingUid + ")");
  15. skip = true;
  16. break;
  17. }
  18. int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
  19. if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
  20. && mService.mAppOpsService.noteOperation(appOp,
  21. filter.receiverList.uid, filter.packageName)
  22. != AppOpsManager.MODE_ALLOWED) {
  23. Slog.w(TAG, "Appop Denial: receiving "
  24. + r.intent.toString()
  25. + " to " + filter.receiverList.app
  26. + " (pid=" + filter.receiverList.pid
  27. + ", uid=" + filter.receiverList.uid + ")"
  28. + " requires appop " + AppOpsManager.permissionToOp(
  29. requiredPermission)
  30. + " due to sender " + r.callerPackage
  31. + " (uid " + r.callingUid + ")");
  32. skip = true;
  33. break;
  34. }
  35. }
  36. }

同上面5.1 发送广播的接口也有带权限的,这里要求接收端也必须具备发送端所要求的权限。

5.3 check 其他权限

除了上面两个权限要求,还会根据当前广播的配对、是否killed等情况确认该广播是否最终放弃发布。

上面权限check 通过的话会进入最终performReceiveLocked() 函数。

5.4 performReceiveLocked()

  1. void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
  2. Intent intent, int resultCode, String data, Bundle extras,
  3. boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
  4. // Send the intent to the receiver asynchronously using one-way binder calls.
  5. if (app != null) {
  6. if (app.thread != null) {
  7. // If we have an app thread, do the call through that so it is
  8. // correctly ordered with other one-way calls.
  9. try {
  10. app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
  11. data, extras, ordered, sticky, sendingUser, app.repProcState);
  12. } catch (RemoteException ex) {
  13. synchronized (mService) {
  14. Slog.w(TAG, "Can't deliver broadcast to " + app.processName
  15. + " (pid " + app.pid + "). Crashing it.");
  16. app.scheduleCrash("can't deliver broadcast");
  17. }
  18. throw ex;
  19. }
  20. } else {
  21. // Application has died. Receiver doesn't exist.
  22. throw new RemoteException("app.thread must not be null");
  23. }
  24. } else {
  25. receiver.performReceive(intent, resultCode, data, extras, ordered,
  26. sticky, sendingUser);
  27. }
  28. }

这里首先判断通过注册进来的广播是什么,因为例子中是通过activity注册的,这里的app参数就是代表activity的进程记录块,receiver这是注册时传给AMS的Binder对象。
在调用后会通过:app.thread.scheduleRegisteredReceiver()函数把广播分发给activity。

5.5 scheduleRegisteredReceiver()

  1. public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
  2. int resultCode, String dataStr, Bundle extras, boolean ordered,
  3. boolean sticky, int sendingUser, int processState) throws RemoteException {
  4. updateProcessState(processState, false);
  5. receiver.performReceive(intent, resultCode, dataStr, extras, ordered,
  6. sticky, sendingUser);
  7. }

终于看到了这里的receiver 对象,这个是在deliverToRegisteredReceiverLocked() 函数中传入的。

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

这里就不细细解释,详细看Android 中broadcast 注册过程解析

5.6 performReceive()

  1. public void performReceive(Intent intent, int resultCode, String data,
  2. Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
  3. final Args args = new Args(intent, resultCode, data, extras, ordered,
  4. sticky, sendingUser);
  5. if (intent == null) {
  6. Log.wtf(TAG, "Null intent received");
  7. } else {
  8. if (ActivityThread.DEBUG_BROADCAST) {
  9. int seq = intent.getIntExtra("seq", -1);
  10. Slog.i(ActivityThread.TAG, "Enqueueing broadcast " + intent.getAction()
  11. + " seq=" + seq + " to " + mReceiver);
  12. }
  13. }
  14. if (intent == null || !mActivityThread.post(args.getRunnable())) {
  15. if (mRegistered && ordered) {
  16. IActivityManager mgr = ActivityManager.getService();
  17. if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
  18. "Finishing sync broadcast to " + mReceiver);
  19. args.sendFinished(mgr);
  20. }
  21. }
  22. }

其中会调用mActivityThread.post(args.getRunnable()),最终调用onReceiver():

  1. try {
  2. ClassLoader cl = mReceiver.getClass().getClassLoader();
  3. intent.setExtrasClassLoader(cl);
  4. intent.prepareToEnterProcess();
  5. setExtrasClassLoader(cl);
  6. receiver.setPendingResult(this);
  7. receiver.onReceive(mContext, intent);

终于看到了onReceiver(),总结示意图如下:

5.7 finish()

  1. if (receiver.getPendingResult() != null) {
  2. finish();
  3. }
  1. public final void finish() {
  2. if (mType == TYPE_COMPONENT) { // 静态注册的广播
  3. final IActivityManager mgr = ActivityManager.getService();
  4. if (QueuedWork.hasPendingWork()) {
  5. QueuedWork.queue(new Runnable() {
  6. @Override public void run() {
  7. if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
  8. "Finishing broadcast after work to component " + mToken);
  9. sendFinished(mgr);
  10. }
  11. }, false);
  12. } else {
  13. sendFinished(mgr);
  14. }
  15. } else if (mOrderedHint && mType != TYPE_UNREGISTERED) {// 动态注册的广播
  16. final IActivityManager mgr = ActivityManager.getService();
  17. sendFinished(mgr);
  18. }
  19. }

主要功能:

静态注册的广播接收者:

  • 当QueuedWork工作未完成, 即SharedPreferences写入磁盘的操作没有完成, 则等待完成再执行sendFinished方法;
  • 当QueuedWork工作已完成, 则直接调用sendFinished方法;

动态注册的广播接收者:

  • 当发送的是串行广播, 则直接调用sendFinished方法。


另外常量参数说明:

  • TYPE_COMPONENT: 静态注册
  • TYPE_REGISTERED: 动态注册
  • TYPE_UNREGISTERED: 取消注册

5.8 sendFinished()

  1. public void sendFinished(IActivityManager am) {
  2. synchronized (this) {
  3. if (mFinished) {
  4. throw new IllegalStateException("Broadcast already finished");
  5. }
  6. mFinished = true; // 置标志,防止 2 次finish
  7. try {
  8. if (mResultExtras != null) {
  9. mResultExtras.setAllowFds(false);
  10. }
  11. if (mOrderedHint) { // 有序广播
  12. am.finishReceiver(mToken, mResultCode, mResultData, mResultExtras,
  13. mAbortBroadcast, mFlags);
  14. } else { // 无序广播
  15. // This broadcast was sent to a component; it is not ordered,
  16. // but we still need to tell the activity manager we are done.
  17. am.finishReceiver(mToken, 0, null, null, false, mFlags);
  18. }
  19. } catch (RemoteException ex) {
  20. }
  21. }
  22. }

其实从这里的mFinished 的标志可以看到其实这里的处理基本是完成了,最后还是会通过am.finishReceiver 来通知AMS 在LoadedApk(注册端) 中的广播处理工作完成。由于是IPC,通过的是AMS 的binder。

5.9 finishReceiver()

  1. public void finishReceiver(IBinder who, int resultCode, String resultData,
  2. Bundle resultExtras, boolean resultAbort, int flags) {
  3. if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + who);
  4. // Refuse possible leaked file descriptors
  5. if (resultExtras != null && resultExtras.hasFileDescriptors()) {
  6. throw new IllegalArgumentException("File descriptors passed in Bundle");
  7. }
  8. final long origId = Binder.clearCallingIdentity();
  9. try {
  10. boolean doNext = false;
  11. BroadcastRecord r;
  12. synchronized(this) {
  13. BroadcastQueue queue = (flags & Intent.FLAG_RECEIVER_FOREGROUND) != 0
  14. ? mFgBroadcastQueue : mBgBroadcastQueue;
  15. r = queue.getMatchingOrderedReceiver(who);
  16. if (r != null) {
  17. doNext = r.queue.finishReceiverLocked(r, resultCode,
  18. resultData, resultExtras, resultAbort, true);
  19. }
  20. }
  21. // 如果还有其他广播,继续执行,不过这里不是从handler 发消息,参数为false
  22. if (doNext) {
  23. r.queue.processNextBroadcast(false);
  24. }
  25. trimApplications();
  26. } finally {
  27. Binder.restoreCallingIdentity(origId);
  28. }
  29. }

至此,广播的发布过程就解析完了。

6. 总结

6.1 BroadcatReceiver 分类

静态广播:通过AndroidManifest.xml 注册的广播

动态广播:通过AMS.registerReceiver注册的广播,注意跟unregisterReceiver() 配套。

6.2 send broadcast 分类

普通广播:sendBroadcast()

有序广播:sendOrderedBroadcast()

粘性广播:sendStickyBroadcast()

6.3 广播处理机制

order = ture

  • 静态注册的广播:串行处理
  • 动态注册的广播:串行处理

order = false

  • 静态注册的广播:串行处理
  • 动态注册的广播:并行处理

6.4 广播中的ANR

ANR时机:只有串行广播才需要考虑超时,因为接收者是串行处理的,前一个receiver处理慢,会影响后一个receiver;并行广播 通过一个循环一次性向所有的receiver分发广播事件,所以不存在彼此影响的问题,则没有广播超时;

  • 串行广播超时情况1:某个广播总处理时间 > 2* receiver总个数 * mTimeoutPeriod, 其中mTimeoutPeriod,前台队列默认为10s,后台队列默认为60s;
  • 串行广播超时情况2:某个receiver的执行时间超过mTimeoutPeriod;

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

闽ICP备14008679号