Broadcast是观察者模式(发布订阅者模式)的应用,用于进程间通信或者进程内通信,如果仅是用在进程内通信则可以选择LocalBroadcastManager更加高效,安全;
在阅读该文章前,最好先阅读EventBus源码解析,EventBus也是观察者模式(发布订阅者模式)的应用,用于进程间通信;
可先阅读Android Binder机制浅析和APP进程和SystemServer进程通信更好的理解Binder通信和APP进程与SystemServer进程间的通信;
四大组件的启动流程,相比来说Service的启动流程相对比较简单些,Broadcast和Activity相对比较复杂;
startService流程
Activity启动流程浅析
以下内容以Android-26的源码来分析的;
//注册进程(APP)
android.content.ContextWrapper
android.content.Context
android.app.ContextImpl
android.app.ActivityManager
//SystemService进程
com.android.server.am.ActivityManagerService
ContextWrapper的registerReceiver()
@Override
public Intent registerReceiver( BroadcastReceiver receiver, IntentFilter filter) {
return mBase.registerReceiver(receiver, filter);
}
Context的registerReceiver()
@Nullable
public abstract Intent registerReceiver(@Nullable BroadcastReceiver receiver,
IntentFilter filter);
ContextImpl的registerReceiver()
@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
return registerReceiver(receiver, filter, null, null);
}
@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
String broadcastPermission, Handler scheduler) {
return registerReceiverInternal(receiver, getUserId(),
filter, broadcastPermission, scheduler, getOuterContext(), 0);
}
Context是抽象类,ContextWrapper相当于是Context的代理类,调用Context的方法,必须要通过ContextWrapper类调用,不直接调用Context类;
ContextImpl是Context的具体实现类;
ContextImpl的registerReceiverInternal()主要是创建IIntentReceiver对象rd,然后通过Binder跨进程通信,调用SystemServer进程的ActivityManagerService的registerReceiver()方法;
private Intent registerReceiverInternal(BroadcastReceiver receiver, int userId,
IntentFilter filter, String broadcastPermission,
Handler scheduler, Context context, int flags) {
IIntentReceiver rd = null;
if (receiver != null) {
if (mPackageInfo != null && context != null) {
if (scheduler == null) {
scheduler = mMainThread.getHandler();
}
rd = mPackageInfo.getReceiverDispatcher(
receiver, context, scheduler,
mMainThread.getInstrumentation(), true);
} else {
if (scheduler == null) {
scheduler = mMainThread.getHandler();
}
//创建ReceiverDispatcher对象接受者分发器;
rd = new LoadedApk.ReceiverDispatcher(
receiver, context, scheduler, null, true).getIIntentReceiver();
}
}
final Intent intent = ActivityManager.getService().registerReceiver(
mMainThread.getApplicationThread(), mBasePackageName, rd, filter,
broadcastPermission, userId, flags);
if (intent != null) {
intent.setExtrasClassLoader(getClassLoader());
intent.prepareToEnterProcess();
}
return intent;
}
ActivityManager的getService()获取IActivityManager对象,使用AIDL跨进程通信大家都比较熟悉,AIDL的实现原理Binder机制,具体的实现过程借用大神Carson_Ho的Android跨进程通信:图文详解来学习。
APP进程和SystemServer进程通信
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
//创建IActivityManager的单例对象;
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
ServiceManager类用于管理所有的系统服务,维护着系统服务和客户端的粘结剂通信。通过getService()方法获取服务,返回的是一个Binder对象,用于与系统做远程通信。
getIServiceManager()方法通过asInterface()方法获取IServiceManager对象,内部调用了ServiceManagerNative和ServiceManagerProxy类。
ActivityManagerService的registerReceiver();
public Intent registerReceiver(IApplicationThread caller, String callerPackage,
IIntentReceiver receiver, IntentFilter filter, String permission, int userId,
int flags) {
ArrayList<Intent> stickyIntents = null;
ProcessRecord callerApp = null;
int callingUid;
int callingPid;
boolean instantApp;
synchronized(this) {
userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true, ALLOW_FULL_ONLY,
"registerReceiver", callerPackage);
//过滤器中的Action迭代器;
Iterator<String> actions = filter.actionsIterator();
//粘性广播的处理过程省略;
//mStickyBroadcasts已经发送的粘性广播;key为userId,value为action为key,
//ArrayList为value的ArrayMap;
}
// The first sticky in the list is returned directly back to the client.
Intent sticky = allSticky != null ? allSticky.get(0) : null;
if (receiver == null) {
return sticky;
}
synchronized (this) {
if (callerApp != null && (callerApp.thread == null
|| callerApp.thread.asBinder() != caller.asBinder())) {
// Original caller already died
return null;
}
//所有已注册的广播HashMap mRegisteredReceivers;
//key是IBinder对象;ReceiverList是ArrayList的子类,广播接受者集合;
ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
//rl为null,创建一个ReceiverList对象,加入到mRegisteredReceivers中;
if (rl == null) {
rl = new ReceiverList(this, callerApp, callingPid, callingUid,
userId, receiver);
if (rl.app != null) {
//添加到receivers中;
rl.app.receivers.add(rl);
} else {
try {
receiver.asBinder().linkToDeath(rl, 0);
} catch (RemoteException e) {
return sticky;
}
rl.linkedToDeath = true;
}
//添加到mRegisteredReceivers中;
mRegisteredReceivers.put(receiver.asBinder(), rl);
}
BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
permission, callingUid, userId, instantApp, visibleToInstantApps);
rl.add(bf);
//mReceiverResolver是IntentResolver类对象,调用addFilter()方法;
mReceiverResolver.addFilter(bf);
//将粘性广播插入到队列中,并且调用scheduleBroadcastsLocked;
return sticky;
}
}
//发送广播进程
android.content.ContextWrapper
android.content.Context
android.app.ContextImpl
android.app.ActivityManager
//SystemService进程
com.android.server.am.ActivityManagerService
com.android.server.am.BroadcastQueue
//动态注册广播接受者,接受广播进程
android.app.ActivityThread内部类ApplicationThread
android.app.LoadedApk内部类ReceiverDispatcher
//有序广播,动态注册--调用下一个广播接受者
android.content.BroadcastReceiver内部类PendingResult
com.android.server.am.ActivityManagerService
com.android.server.am.BroadcastQueue
//静态注册广播接受者
android.app.ActivityThread内部类ApplicationThread
android.app.ActivityThread
android.content.BroadcastReceiver内部类PendingResult
com.android.server.am.ActivityManagerService
com.android.server.am.BroadcastQueue
ContextWrapper的sendBroadcast()
@Override
public void sendBroadcast(Intent intent) {
mBase.sendBroadcast(intent);
}
Context的sendBroadcast()
public abstract void sendBroadcast(@RequiresPermission Intent intent);
ContextImpl的sendBroadcast()通过Binde机制进行跨进程通信调用SystemService进程的ActivityManagerService的broadcastIntent()方法;
@Override
public void sendBroadcast(Intent intent) {
warnIfCallingFromSystemProcess();
String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntent(
mMainThread.getApplicationThread(), intent, resolvedType, null,
Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, false,
getUserId());
}
}
ActivityManagerService的broadcastIntent()调用broadcastIntentLocked()方法;
public final int broadcastIntent() {
synchronized(this) {
int res = broadcastIntentLocked();
Binder.restoreCallingIdentity(origId);
return res;
}
}
ActivityManagerService的broadcastIntentLocked()是sendBroadcast最核心的方法之一,主要是将不同类型的广播,不同的注册方式创建的BroadcastRecord对象插入到BroadcastQueued的队列中,将主要做以下几件事:
1)将粘性广播添加到mStickyBroadcasts中,保存;
2)确定广播接受者,对将无序的广播(即普通广播),并且动态注册BroadcastReceiver插入到BroadcastQueue类的广播队列mParallelBroadcasts中,并发出Handler插入消息;
3)如果广播是无序的广播(即普通广播)会将静态注册的BroadcastReceiver插入到BroadcastQueue的广播队列mOrderedBroadcasts中,并触发广播发送流程;
4)如果是有序广播,把静态BroadcastReceiver和动态BroadcastReceiver按照优先级合并到receivers中,再将剩余的动态注册的广播插入到receivers中,最后添加到BroadcastQueue的广播队列mOrderedBroadcasts中,并触发广播发送流程。
ActivityManagerService的broadcastIntentLocked()证明了动态注册的BroadcastReceiver在广播在优先级相同的情况下先于静态注册的BroadcastReceiver执行;
final int broadcastIntentLocked() {
final String action = intent.getAction();
//1)
//将粘性广播往SparseArray>> mStickyBroadcasts中添加;
//key为userId,value为action为key,ArrayList为value的ArrayMap;
if (sticky) {
ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
....
}
//确定广播接受者;
//2)
//receivers主要用于保存匹配当前广播的静态注册的BroadcastReceiver;
//若当前广播是有序广播时,还会插入动态注册的BroadcastReceiver;
List receivers = null;
//registeredReceivers用于保存匹配当前广播的动态注册的BroadcastReceiver;
List<BroadcastFilter> registeredReceivers = null;
// Need to resolve the intent to interested receivers...
if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
== 0) {
//利用PKMS的queryIntentReceivers接口,查询满足条件的静态BroadcastReceiver
receivers = collectReceiverComponents(intent, resolvedType, callingUid, users);
}
//默认情况下为null;
if (intent.getComponent() == null) {
//主要通过 mReceiverResolver.queryIntent()方法获取注册的接受者;
registeredReceivers = mReceiverResolver.queryIntent(intent,
resolvedType, false /*defaultOnly*/, userId);
}
//先处理动态注册的BroadcastReceiver对应的广播
int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
//处理无序的广播即普通的广播,并且有接受者;
if (!ordered && NR > 0) {
//根据flag判断返回前台广播队列还是后台广播队列;
final BroadcastQueue queue = broadcastQueueForIntent(intent);
//创建BroadcastRecord对象;参数包含queue和registeredReceivers;
BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
callerPackage, callingPid, callingUid, callerInstantApp, resolvedType,
requiredPermissions, appOp, brOptions, registeredReceivers, resultTo,
resultCode, resultData, resultExtras, ordered, sticky, false, userId);
//replaceParallelBroadcastLocked()队列中有相同的Intent,替换;
final boolean replaced = replacePending
&& (queue.replaceParallelBroadcastLocked(r) != null);
//不存在相同的Intent,将BroadcastRecord对象添加到队列中,并且调用scheduleBroadcastsLocked()方法;
if (!replaced) {
queue.enqueueParallelBroadcastLocked(r);
queue.scheduleBroadcastsLocked();
}
registeredReceivers = null;
NR = 0;
}
//将receivers和registerReceiver合并到一个列表(receivers)中。
//receivers为静态BroadcastReceiver集合;
int ir = 0;
if (receivers != null) {
int NT = receivers != null ? receivers.size() : 0;
int it = 0;
ResolveInfo curt = null;
BroadcastFilter curr = null;
//NT对应的是静态BroadcastReceiver的数量
//NR对应的是动态BroadcastReceiver的数量
//若发送的是无序广播,此时NR为0,不会进入下面的循环;
//若是有序广播,才会进入下面两个while循环,将静态注册的BroadcastReceiver和动态注册的
//BroadcastReceiver按照优先级合并到一起;如果动态注解的BroadcastReceiver优先级大于等于静态BroadcastReceiver,则放在静态的前面;
while (it < NT && ir < NR) {
if (curt == null) {
curt = (ResolveInfo)receivers.get(it);
}
if (curr == null) {
curr = registeredReceivers.get(ir);
}
//动态优先级大于静态时,将动态插入到receivers中
if (curr.getPriority() >= curt.priority) {
// Insert this broadcast record into the final list.
receivers.add(it, curr);
ir++;
curr = null;
it++;
NT++;
} else {
// Skip to the next ResolveInfo in the final list.
it++;
curt = null;
}
}
}
//把剩下的动态BroadcastReceiver插入到receivers中;
while (ir < NR) {
if (receivers == null) {
receivers = new ArrayList();
}
receivers.add(registeredReceivers.get(ir));
ir++;
}
if ((receivers != null && receivers.size() > 0) || resultTo != null) {
BroadcastQueue queue = broadcastQueueForIntent(intent);
BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
callerPackage, callingPid, callingUid, callerInstantApp, resolvedType,
requiredPermissions, appOp, brOptions, receivers, resultTo, resultCode,
resultData, resultExtras, ordered, sticky, false, userId);
//在mOrderedBroadcasts中是否已经存在相同Intent;
final BroadcastRecord oldRecord =
replacePending ? queue.replaceOrderedBroadcastLocked(r) : null;
if (oldRecord != null) {
//替换后,调用BroadcastQueue的performReceiveLocked()。
if (oldRecord.resultTo != null) {
final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent);
try {
oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo,
oldRecord.intent,
Activity.RESULT_CANCELED, null, null,
false, false, oldRecord.userId);
}
}
} else {
//不存在,直接插入到mOrderedBroadcasts中;
queue.enqueueOrderedBroadcastLocked(r);
queue.scheduleBroadcastsLocked();
}
} else {}
return ActivityManager.BROADCAST_SUCCESS;
}
BroadcastQueue类最核心的地方,用来存储Intent,并且将广播发送给接受者;
public final class BroadcastQueue {
//超时时间,由ActivityManagerService的构造函数可知前台广播超时时间为10s,后台广播超时时间为60s;
final long mTimeoutPeriod;
final boolean mDelayBehindServices;
//并发广播队列,用来存储无序广播(普通广播)并且是动态注册的;
final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
//顺序广播队列,用来存储无序广播(普通广播)静态注册的和有序广播;
final ArrayList<BroadcastRecord> mOrderedBroadcasts = new ArrayList<>();
final BroadcastHandler mHandler;
private final class BroadcastHandler extends Handler {
public BroadcastHandler(Looper looper) {
super(looper, null, true);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
//调用processNextBroadcast();
case BROADCAST_INTENT_MSG: {
processNextBroadcast(true);
} break;
case BROADCAST_TIMEOUT_MSG: {
synchronized (mService) {
broadcastTimeoutLocked(true);
}
} break;
}
}
}
BroadcastQueue(ActivityManagerService service, Handler handler,
String name, long timeoutPeriod, boolean allowDelayBehindServices) {
mService = service;
mHandler = new BroadcastHandler(handler.getLooper());
mQueueName = name;
mTimeoutPeriod = timeoutPeriod;
mDelayBehindServices = allowDelayBehindServices;
}
//往并发广播队列添加BroadcastRecord;
public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
mParallelBroadcasts.add(r);
enqueueBroadcastHelper(r);
}
//往顺序广播队列添加BroadcastRecord;
public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
mOrderedBroadcasts.add(r);
enqueueBroadcastHelper(r);
}
//发送Handler消息;
public void scheduleBroadcastsLocked() {
if (mBroadcastsScheduled) {
return;
}
mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
mBroadcastsScheduled = true;
}
BroadcastQueue的processNextBroadcast()主要是向广播接受者发送广播,是sendBroadcast最核心的地方之一,主要做了一下几件事:
1)先发送普通广播动态注册的,调用deliverToRegisteredReceiverLocked();进而主要调用performReceiveLocked()方法;
2)处理动态注册的有序广播,和普通广播一样,也是调用deliverToRegisteredReceiverLocked()方法;
3)处理静态注册的广播,调用processCurBroadcastLocked()方法;
静态注册的普通广播和有序广播,每次处理完当前接受者之后,才会处理下一个广播接受者;
BroadcastQueue的processNext
final void processNextBroadcast(boolean fromMsg) {
synchronized(mService) {
BroadcastRecord r;
if (fromMsg) {
mBroadcastsScheduled = false;
}
//1:立即发送非序列化的广播;
while (mParallelBroadcasts.size() > 0) {
//从队列头开始;
r = mParallelBroadcasts.remove(0);
r.dispatchTime = SystemClock.uptimeMillis();
r.dispatchClockTime = System.currentTimeMillis();
//广播接收者的数量;
final int N = r.receivers.size();
//向广播的接受者发送广播;
for (int i=0; i<N; i++) {
Object target = r.receivers.get(i);
deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
}
addBroadcastToHistoryLocked(r);
}
//2:处理静态注册的无序广播和有序广播;需要依次向每个BroadcastReceiver发送广播,前一个处理完毕后才能发送下一个广播
boolean looped = false;
//do..while循环主要是从mOrderedBroadcasts队列中取出队列头的BroadcastRecord对象r;
//当对象r广播被处理完成或者被中断,则从队列中删除,继续循环,取出下一个BroadcastRecord对象;
do {
//当mOrderedBroadcasts为空,return;
if (mOrderedBroadcasts.size() == 0) {
return;
}
//从有序广播队列头取出元素;
r = mOrderedBroadcasts.get(0);
int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
//如果广播处理完,或中途被取消等情况;否则无法将r==null,直接跳出do..while循环;
if (r.receivers == null || r.nextReceiver >= numReceivers
|| r.resultAbort || forceReceive) {
if (r.resultTo != null) {
//广播处理完毕,将该广播的处理结果发送给resultTo对应BroadcastReceiver;
performReceiveLocked(r.callerApp, r.resultTo,
new Intent(r.intent), r.resultCode,
r.resultData, r.resultExtras, false, false, r.userId);
}
//取消超时的广播;
cancelBroadcastTimeoutLocked();
addBroadcastToHistoryLocked(r);
//对队列头删除元素;
mOrderedBroadcasts.remove(0);
r = null;
looped = true;
continue;
}
} while (r == null);
//该广播的下一个接受者;
int recIdx = r.nextReceiver++;
//receiver启动时间;
r.receiverTime = SystemClock.uptimeMillis();
//取出下一个广播接受者;
final Object nextReceiver = r.receivers.get(recIdx);
//有序广播,如果是动态注册的,调用deliverToRegisteredReceiverLocked(),必须等待处理结果,才能进行下一次发送过程;
if (nextReceiver instanceof BroadcastFilter) {
BroadcastFilter filter = (BroadcastFilter)nextReceiver;
deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
return;
}
//开始处理静态广播
ResolveInfo info = (ResolveInfo)nextReceiver;
//得到静态广播对应的组件名
ComponentName component = new ComponentName(
info.activityInfo.applicationInfo.packageName,
info.activityInfo.name);
//BroadcastReceiver对应进程启动时,调用ActivityThread的内部类ApplicationThread的scheduleReceiver();
if (app != null && app.thread != null && !app.killed) {
try {
app.addPackage(info.activityInfo.packageName,
info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
processCurBroadcastLocked(r, app);
return;
} catch (RuntimeException e) {
return;
}
}
//启动进程处理广播
if ((r.curApp=mService.startProcessLocked(targetProcess,
info.activityInfo.applicationInfo, true,
r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
"broadcast", r.curComponent,
(r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
== null) {
}
}
}
动态注册的广播(无论普通广播还是有序广播):都调用BroadQueue的deliverToRegisteredReceiverLocked(),除了对BroadcastRecord状态的改变,主要调用performReceiveLocked()方法;
BroadcastQueue的performReceiveLocked(),不管app是否为null,最终都会调用LoadedApk静态内部类ReceiverDispatcher的静态内部类InnerReceiver的performReceive()方法。
void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Intent intent, int resultCode, String data, Bundle extras,
boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
// Send the intent to the receiver asynchronously using one-way binder calls.
//异步将Intent发送给接受者;
if (app != null) {
if (app.thread != null) {
try {
//调用ActivityThread的内部类ApplicationThread的scheduleRegisteredReceiver()方法
app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
data, extras, ordered, sticky, sendingUser, app.repProcState);
}
}
} else {
receiver.performReceive(intent, resultCode, data, extras, ordered,
sticky, sendingUser);
}
}
静态注册的广播:调用BroadcastQueue的processCurBroadcastLocked()主要是跨进程调用接受Broadcast进程的ActivityThread的内部类ApplicationThread的scheduleReceiver()方法,发送Handler消息H.RECEIVER;进而调用ActivityThread的handleReceiver()方法;
private final void processCurBroadcastLocked(BroadcastRecord r,
ProcessRecord app) throws RemoteException {
boolean started = false;
try {
app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
app.repProcState);
started = true;
}
}
LoadedApk静态内部类ReceiverDispatcher的静态内部类InnerReceiver的performReceive()直接调用LoadedApk静态内部类ReceiverDispatcher的performReceive();
LoadedApk静态内部类ReceiverDispatcher的performReceive()主要是调用Handler的post()方法执行Args的getRunnable()方法;
public void performReceive(Intent intent, int resultCode, String data,
Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
//Args的父类为BroadcastReceiver.PendingResult;
final Args args = new Args(intent, resultCode, data, extras, ordered,
sticky, sendingUser);
//handler调用args.getRunnable();如果想MessageQueue队列添加Message成功则返回true;
if (intent == null || !mActivityThread.post(args.getRunnable())) {
if (mRegistered && ordered) {
IActivityManager mgr = ActivityManager.getService();
args.sendFinished(mgr);
}
}
}
LoadedApk静态内部类ReceiverDispatcher的内部类Args的getRunnable():调用BroadcastReceiver的onReceive()方法;
如果广播处理完成,是有序广播,调用BroadcastReceiver的sendFinished(),进而跨进程调用ActivityManagerService的finishReceiver()方法;进而调用BroadcastQueue的processNextBroadcast()方法;
有序广播,每次处理完当前接受者之后,才会处理下一个广播接受者
public final Runnable getRunnable() {
return () -> {
final BroadcastReceiver receiver = mReceiver;
final boolean ordered = mOrdered;
if (receiver == null || intent == null || mForgotten) {
if (mRegistered && ordered) {
sendFinished(mgr);
}
return;
}
try {
ClassLoader cl = mReceiver.getClass().getClassLoader();
intent.setExtrasClassLoader(cl);
intent.prepareToEnterProcess();
setExtrasClassLoader(cl);
receiver.setPendingResult(this);
//调用BroadcastReceiver的onReceive()方法;
receiver.onReceive(mContext, intent);
}
};
}
调用BroadcastQueue的processCurBroadcastLocked()方法,跨进程通信,调用ActivityThread的内部类ApplicationThread的scheduleReceiver()方法;scheduleReceiver()发送H.RECEIVER,进而调用ActivityThread的handleReceiver()方法;
ActivityThread的handleReceiver()方法通过反射创建BroadcastReceiver实例,调用onReceive()方法;
如果广播处理完成,进而调用BroadcastReceiver的sendFinished()方法,进而跨进程调用ActivityManagerService的finishReceiver()方法;进而调用BroadcastQueue的processNextBroadcast()方法;
静态注册的广播接受者,每次处理完当前接受者之后,才会处理下一个广播接受者
private void handleReceiver(ReceiverData data) {
String component = data.intent.getComponent().getClassName();
LoadedApk packageInfo = getPackageInfoNoCheck(
data.info.applicationInfo, data.compatInfo);
Application app;
BroadcastReceiver receiver;
ContextImpl context;
app = packageInfo.makeApplication(false, mInstrumentation);
context = (ContextImpl) app.getBaseContext();
if (data.info.splitName != null) {
context = (ContextImpl) context.createContextForSplit(data.info.splitName);
}
java.lang.ClassLoader cl = context.getClassLoader();
data.intent.setExtrasClassLoader(cl);
data.intent.prepareToEnterProcess();
data.setExtrasClassLoader(cl);
//通过反射创建BroadcastReceiver实例;
receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
try {
sCurrentBroadcastIntent.set(data.intent);
receiver.setPendingResult(data);
//调用onReceive()方法;
receiver.onReceive(context.getReceiverRestrictedContext(),
data.intent);
} finally {
sCurrentBroadcastIntent.set(null);
}
//进而调用BroadcastReceiver的sendFinished()方法
if (receiver.getPendingResult() != null) {
data.finish();
}
}
直接看SystemService进程的ActivityManagerService类的unregisterReceiver(),将接受者从receivers集合中删除;
public void unregisterReceiver(IIntentReceiver receiver) {
final long origId = Binder.clearCallingIdentity();
try {
boolean doTrim = false;
synchronized(this) {
ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
if (rl != null) {
final BroadcastRecord r = rl.curBroadcast;
if (r != null && r == r.queue.getMatchingOrderedReceiver(r)) {
final boolean doNext = r.queue.finishReceiverLocked(
r, r.resultCode, r.resultData, r.resultExtras,
r.resultAbort, false);
if (doNext) {
doTrim = true;
r.queue.processNextBroadcast(false);
}
}
//从receivers中删除接受者;
if (rl.app != null) {
rl.app.receivers.remove(rl);
}
removeReceiverLocked(rl);
if (rl.linkedToDeath) {
rl.linkedToDeath = false;
rl.receiver.asBinder().unlinkToDeath(rl, 0);
}
}
}
if (doTrim) {
trimApplications();
return;
}
} finally {
Binder.restoreCallingIdentity(origId);
}
}
以上就是广播的主要内容,如有问题,请多指教,谢谢!