从registerReceiver(BroadcastReceiver receiver,IntentFilter filter)出发
所经历的类和方法:registerReceiver(receiver,filter)–>ContextWrapper.java$registerReceiver(receiver,filter);
@Override
public Intent registerReceiver(
BroadcastReceiver receiver, IntentFilter filter) {
return mBase.registerReceiver(receiver, filter);//Context mBase
}
Context是接口,其实现类ContextImpl,因此其具体实现是ContextImpl$reisterReceiver(receiver,filter);
@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
return registerReceiver(receiver, filter, null, null);
}
@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
int flags) {
return registerReceiver(receiver, filter, null, null, flags);
}
@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
String broadcastPermission, Handler scheduler) {
return registerReceiverInternal(receiver, getUserId(),
filter, broadcastPermission, scheduler, getOuterContext(), 0);
}
用以上代码可知调用registerReceiver以后其内部调用了其重载函数,其重载函数又进一步调了registerReceiverInternal()方法
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(); //1
}
rd = mPackageInfo.getReceiverDispatcher(
receiver, context, scheduler,
mMainThread.getInstrumentation(), true);
} else {
if (scheduler == null) {
scheduler = mMainThread.getHandler();
}
rd = new LoadedApk.ReceiverDispatcher(
receiver, context, scheduler, null, true).getIIntentReceiver();
}
}
try {
final Intent intent = ActivityManager.getService().registerReceiver(
mMainThread.getApplicationThread(), mBasePackageName, rd, filter,
broadcastPermission, userId, flags);
if (intent != null) {
intent.setExtrasClassLoader(getClassLoader());
intent.prepareToEnterProcess();
}
return intent;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
IIntentReceiver :IIntentReceiver其实是一个AIDL接口,内部就一个方法performReceive(…);
mPackageInfo:ContextImpl导入的一个LoadedApk的实例,是用来处理广播接收的。
以上参数context通过getOuterContext获取注册广播时所在的context,方法走到//1处,scheduler = mMainThread.getHandler();该scheduler是一个Handler类型,mMainThread是ActivityThread类型,这里handler主要用来负责分发AMS发送过来的广播用的。
public final class ActivityThread {
......
final H mH = new H();
private final class H extends Handler {
......
public void handleMessage(Message msg) {
......
switch (msg.what) {
......
}
......
}
.....
}
......
final Handler getHandler() {
return mH;
}
获取完scheduler(Handler),执行 rd = mPackageInfo.getReceiverDispatcher(…),
public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r,
Context context, Handler handler,
Instrumentation instrumentation, boolean registered) {
synchronized (mReceivers) {
LoadedApk.ReceiverDispatcher rd &