在Android中,BroadcastReceiver分动态注册和静态注册. 静态注册的一个优势就是:当你的BroadcastReceiver可以接受系统中
某个broadcast时,系统会自动启动你的程序,从而让BroadcastReceiver完成相关处理; 而动态注册则只有在程序运行时且没有
unregisterReceiver才能接收到broadcast.
此时,假设我们要在系统开机后,要对SIM卡联系人进行读取操作,那么我们应该如何注册自己的BroadcastReceiver呢?
方案一:
通过静态注册receiver来处理ACTION_SIM_STATE_CHANGED的broadcast,当icc state为LOADED时,读取SIM卡联系人.
这是一种比较常规的做法. 但是这个方案有一个比较严重的问题,那就是接收到broadcast的时机太晚了。结果就是,可能开机几
分钟过去了,SIM卡联系人却还没加载出来。
通过查看IccCardProxy中broadcastIccStateChangedIntent()函数的代码,我们发现,它发送的就是一个sticky broadcast
ActivityManagerNative.broadcastStickyIntent(intent, READ_PHONE_STATE, UserHandle.USER_ALL)
按照常理来推断,一个sticky的broadcast不应该需要耗时这么久的。
那问题究竟出在什么地方了呢?
在调查这个问题之前,我们先简单看一下,静态注册的receiver和动态注册的receiver是如何被管理的呢?
静态注册receiver:
简单讲,系统启动时,创建PackageManagerService对象,简称PMS,然后通过scanDirLI函数对各个路径进行扫描,保存receiver等等
main[] // PackageManagerService.java
PackageManagerService()
scanDirLI()
scanPackageLI(File scanFile, int parseFlags, int scanFlags, long currentTime, UserHandle user)
parsePackage() // PackageParser.java
// scanPackageLI(PackageParser…)调用scanPackageDirtyLI来进一步处理parsePackage()生成的PackageParser.Package对象pkg
// scanPackageDirtyLI将pkg中的receiver添加到PMS的mReceivers中(具体代码:mReceivers.addActivity(a, “receiver”)),
// 并将pkg添加到PMS的mPackages中(具体代码:mPackages.put(pkg.applicationInfo.packageName, pkg))
scanPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, long currentTime, UserHandle user) // PackageManagerService.java
parseBaseApk(File apkFile, AssetManager assets, int flags) // PackageParser.java
parseBaseApk(Resources res, XmlResourceParser parser, int flags, String[] outError)
parseBaseApplication() // // 将生成的receiver放到receivers中
} else if (tagName.equals("receiver")) { Activity a = parseActivity(owner, res, parser, attrs, flags, outError, true, false); if (a == null) { mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED; return false; } owner.receivers.add(a); } else if (tagName.equals("service")) {
通过上面的简单分析,我们可以发现所有静态注册的receiver是通过PMS进行管理的.
动态注册的receiver:
相比静态注册,动态注册的流程要简单许多.
registerReceiver(BroadcastReceiver receiver, IntentFilter filter) // ContextImpl.java
registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)
registerReceiverInternal()
registerReceiver() // AMS
在AMS的registerReceiver函数中,receiver和broadcast filter相关信息被放到了mRegisteredReceivers和mReceiverResolver中.
了解了静态注册和动态注册receiver在PMS和AMS中的大致流程后,再来看下IccCardProxy发送sticky broadcast时AMS的大概流程.
broadcastStickyIntent(intent, READ_PHONE_STATE, UserHandle.USER_ALL) // ActivityManagerNative.java
broadcastIntent() // ActivityManagerService.java 简称AMS
broadcastIntentLocked()
下面贴一下broadcastIntentLocked中比较重要的处理
private final int broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle map, String requiredPermission, int appOp, boolean ordered, boolean sticky, int callingPid, int callingUid, int userId) { intent = new Intent(intent); // By default broadcasts do not go to stopped apps. intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); ...... userId = handleIncomingUser(callingPid, callingUid, userId, true, ALLOW_NON_FULL, "broadcast", callerPackage); ...... /* * Prevent non-system code (defined here to be non-persistent * processes) from sending protected broadcasts. */ int callingAppId = UserHandle.getAppId(callingUid); ...... // Figure out who all will receive this broadcast. List receivers = null; // PMS中的结果 List<BroadcastFilter> registeredReceivers = null; // AMS中的结果 // Need to resolve the intent to interested receivers... if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { // 向PMS查询符合条件的receiver receivers = collectReceiverComponents(intent, resolvedType, callingUid, users); } if (intent.getComponent() == null) { if (userId == UserHandle.USER_ALL && callingUid == Process.SHELL_UID) { ...... } else {
// 向AMS查询符合条件的receiver registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false, userId); } } final boolean replacePending = (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0; ...... // 注意,这里用的是从AMS中查询出来的符合条件的receiver int NR = registeredReceivers != null ? registeredReceivers.size() : 0; if (!ordered && NR > 0) { // If we are not serializing this broadcast, then send the // registered receivers separately so they don't wait for the // components to be launched. final BroadcastQueue queue = broadcastQueueForIntent(intent); BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage, callingPid, callingUid, resolvedType, requiredPermission, appOp, registeredReceivers, resultTo, resultCode, resultData, map, ordered, sticky, false, userId); if (DEBUG_BROADCAST) Slog.v( TAG, "Enqueueing parallel broadcast " + r); final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r); if (!replaced) { queue.enqueueParallelBroadcastLocked(r); queue.scheduleBroadcastsLocked(); } registeredReceivers = null; NR = 0; } ...... if ((receivers != null && receivers.size() > 0) || resultTo != null) { BroadcastQueue queue = broadcastQueueForIntent(intent); BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage, callingPid, callingUid, resolvedType, requiredPermission, appOp, receivers, resultTo, resultCode, resultData, map, ordered, sticky, false, userId); if (DEBUG_BROADCAST) Slog.v( TAG, "Enqueueing ordered broadcast " + r + ": prev had " + queue.mOrderedBroadcasts.size()); if (DEBUG_BROADCAST) { int seq = r.intent.getIntExtra("seq", -1); Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq); } boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r); if (!replaced) { // 注意,被放到ordered broadcast中了! queue.enqueueOrderedBroadcastLocked(r); queue.scheduleBroadcastsLocked(); } } return ActivityManager.BROADCAST_SUCCESS; }
collectReceiverComponents()和mReceiverResolver.queryIntent()是broadcastIntentLocked()中两个重要的函数调用.分别初始化了broadcastIntentLocked()中的receivers和registeredReceivers变量.
collectReceiverComponents()基本是通过调用AppGlobals.getPackageManager().queryIntentReceivers()来查询符合条件的receiver,
也就是PMS的queryIntentReceivers()函数进行查询,进而通过PMS中mReceivers变量的queryIntent来执行查询操作.
可见,collectReceiverComponents()最终查询到的是静态注册的符合条件的receiver.
再来简单看下mReceiverResolver.queryIntent()方法的查询结果. 我们在执行AMS的registerReceiver()时,将broadcast以及broadcast filter相关的
信息放到了mReceiverResolver中,因此,这里查询到的是所有符合条件的动态注册的receiver.
最终,符合条件的静态注册的receiver被保存在broadcastIntentLocked函数中receivers变量中;符合条件的动态注册的receiver被保存在registeredReceivers变量中。
在接下来enqueueParallelBroadcastLocked时,却只使用了registeredReceivers,即动态注册的receiver. 而静态注册的receiver却被enqueueOrderedBroadcastLocked
放到了ordered broadcast队列中!
下面再来简单看下BroadcastQueue对broadcast的处理流程:
scheduleBroadcastsLocked()
handleMessage() // BroadcastQueue$BroadcastHandler
processNextBroadcast()
deliverToRegisteredReceiverLocked() // non-ordered
performReceiveLocked()
scheduleRegisteredReceiver() // ActivityThread$ApplicationThread
performReceive() // LoadedApk$ReceiverDispatcher
mActivityThread.post(args)
run() // LoadedApk$Args
receiver.onReceive(mContext, intent) // 执行BroadcastReceiver的onReceive方法
processCurBroadcastLocked() // ordered
scheduleReceiver() // ActivityThread$ApplicationThread
handleMessage() // ActivityThread$H
handleReceiver() // ActivityThread
receiver.onReceive(context.getReceiverRestrictedContext(), data.intent) // 执行BroadcastReceiver的onReceive方法
由于ordered broadcast是一条一条来处理,也就不难发现为什么我们静态注册的接收ACTION_SIM_STATE_CHANGED的broadcast receiver很晚才能被启动了.
既然静态注册的receiver只能接受ordered broadcast后,如果想提升接收broadcast的速度,那我们只能使用动态注册receiver了。也就引出了我们的第二个方案.
方案二:
通过自定义Application并在自定义Application中动态注册receiver来处理ACTION_SIM_STATE_CHANGED的broadcast,在AndroidManifest.xml中声明时为自定义
的application添加android:persistent=”true”属性. 这样就可以大幅提升接收ACTION_SIM_STATE_CHANGED的速度,但这是为什么呢?
在AMS的systemReady()中将通过PMS的getPersistentApplications()获得所有persistent属性为true的程序,并将他们启动起来. 即在进入launcher之前就被启动了.
而我们在自定义的Application的onCreate()中注册receiver, 来接收ACTION_SIM_STATE_CHANGED的broadcast,我们的receiver将被AMS管理,进而我们就可以更
快的接收到broadcast了(参考上文对AMS中broadcastIntentLocked()的分析). 但是这个方案也不是完美的,因为它声明了persistent=“true”,会占用内存以及增加开机时间.
自定义Application的代码:
public class MyApp extends Application { private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO } }; @Override public void onCreate() { super.onCreate(); IntentFilter intentFilter = new IntentFilter(TelephonyIntents.ACTION_SIM_STATE_CHANGED); intentFilter.addAction(Intent.ACTION_BOOT_COMPLETED); registerReceiver(mReceiver, intentFilter); } }
在AndroidManifest中的声明:
<application android:name="MyApp" android:label="@string/app_name" android:persistent="true"> ... </application>
不止ACTION_SIM_STATE_CHANGED,其它的broadcast receiver也可以采用方案二的做法来更快速的接收broadcast,就看自己有没有这个需要了.
写的比较仓促,有纰漏之处,敬请批评指正!