broadcoast发送与接收

  • content
    {:toc}

    开始

上一节已经讲过了启动的过程,其中第三小步1.1里面的2.x系列将了发送回来的过程,这篇文章会继续加上。

Step 1

1
2
3
4
5
6
7
8
9
10
AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
@Override
public void run() {
Intent intent = new Intent();
//子线程发出一个带有这个信号的intent
intent.setAction(Constant.MY_BROADCAST_ACTION);
intent.putExtra("mydata", "你好");
sendBroadcast(intent);
}
});

特意在子线程中发出,其实都一样,消息接收的时候,会回到主线,因此,在BroadcastReceiver中的onReceive尽量不要做耗时操作。

step 2

1
2
3
ContextWrapper#sendBroadcast()  --> ContextImpl#sendBroadcast()
然后在ContextImpl的sendBroadcast中调用了ActivityManager.getService().broadcastIntent(...)
//实际上这个就是AIDL的IActivityManager的一个proxy对象调用的broadcastIntent方法

最终就是把 Intent 中的action找 AMS 要对应的broadcast的action去发送

step 3 ActivityManagerService#broadcastIntent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public final int broadcastIntent(IApplicationThread caller,
Intent intent, String resolvedType, IIntentReceiver resultTo,
int resultCode, String resultData, Bundle resultExtras,
String[] requiredPermissions, int appOp, Bundle bOptions,
boolean serialized, boolean sticky, int userId) {
synchronized(this) {
intent = verifyBroadcastLocked(intent);
final long origId = Binder.clearCallingIdentity();
//....
// 1.
int res = broadcastIntentLocked(callerApp, callerApp != null ? callerApp.info.packageName : null, intent, resolvedType, resultTo, resultCode, resultData, resultExtras,requiredPermissions, appOp, bOptions, serialized, sticky,callingPid, callingUid, userId);
Binder.restoreCallingIdentity(origId);
return res;
}
}

broadcastIntent 最后调用了broadcastIntentLocked

step 4 ActivityManagerService#broadcastIntentLocked