RePlugin解析之BroadcastReceiver

引言

我看到的分析RePlugin中BroadcastReceiver的文章中,基本都放在了对于插件中静态注册的BroadcastReceiver的处理上,却忽略了还有动态注册的BroadcastReceiver,而实际上这部分也很重要,而且replugin-plugin-gradle中有一项重要的内容就是将插件中LocalBroadcastManager的调用替换为PluginLocalBroadcastManager的调用

1.插件中静态注册的BroadcastReceiver

RePlugin解析之插件的安装与加载一文中有分析Loader中的loadDex()方法,在这个方法中有一个regReceivers()的调用,这个调用的目的就是动态注册插件中静态的BroadcastReceiver,这个方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 动态注册插件中静态声明的 receiver 到常驻进程
*
* @throws android.os.RemoteException
*/
private void regReceivers() throws android.os.RemoteException {
String plugin = mPluginObj.mInfo.getName();
if (mPluginHost == null) {
mPluginHost = getPluginHost();
}
if (mPluginHost != null) {
mPluginHost.regReceiver(plugin, ManifestParser.INS.getReceiverFilterMap(plugin));
}
}

注意mPluginHost只是IPluginHost的代理,通过它可以进行IPC调用到PmHostSvc中的regReceiver()方法,而这里显然就是将解析插件Manifest得到的BroadcastReceiver的IntentFilter信息传递过去, PmHostSvc.regReceiver()方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public void regReceiver(String plugin, Map rcvFilMap) throws RemoteException {
PluginInfo pi = MP.getPlugin(plugin, false);
if (pi == null || pi.getFrameworkVersion() < 4) {
return;
}
HashMap<String, List<IntentFilter>> receiverFilterMap = (HashMap<String, List<IntentFilter>>) rcvFilMap;
// 遍历此插件中所有静态声明的 Receiver
for (HashMap.Entry<String, List<IntentFilter>> entry : receiverFilterMap.entrySet()) {
if (mReceiverProxy == null) {
mReceiverProxy = new PluginReceiverProxy();
mReceiverProxy.setActionPluginMap(mActionPluginComponents);
}
/* 保存 action-plugin-receiver 的关系 */
String receiver = entry.getKey();
List<IntentFilter> filters = entry.getValue();
if (filters != null) {
for (IntentFilter filter : filters) {
int actionCount = filter.countActions();
while (actionCount >= 1) {
saveAction(filter.getAction(actionCount - 1), plugin, receiver);
actionCount--;
}
// 注册 Receiver
mContext.registerReceiver(mReceiverProxy, filter);
}
}
}
}

注意由于aidl中map不能带有类型,所以这里进行了强转。这个方法中有两个重点,第一个是saveAction(),即保存action-plugin-receiver的关系 ,它们的关系如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 保存 action 与 plugin,receiver 的对应关系
* <p>
* -------------------------------------------------------
* | action | action |
* -------------------------------------------------------
* | plugin | plugin | plugin | ... |
* -------------------------------------------------------
* | receiver | receiver | receiver | ... |
* | receiver | receiver | receiver | ... |
* | receiver | receiver | receiver | ... |
* | ... | ... | ... | ... |
* -------------------------------------------------------
* <p>
* Map < Action, Map < Plugin, List< Receiver >>>
*/
private final HashMap<String, HashMap<String, List<String>>> mActionPluginComponents = new HashMap<>();

看完这个图之后就很好理解了。

regReceiver()中另外一个重点是BroadcastReceiver的注册,从这里可以看出,所有的广播都是注册在mReceiverProxy这个代理的广播接收器上的,它是PluginReceiverProxy对象,onReceive()方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null || mActionPluginComponents == null) {
return;
}
String action = intent.getAction();
if (!TextUtils.isEmpty(action)) {
...
// 根据 action 取得 map<plugin, List<receiver>>
HashMap<String, List<String>> pc = mActionPluginComponents.get(action);
if (pc != null) {
// 遍历每一个插件
for (HashMap.Entry<String, List<String>> entry : pc.entrySet()) {
String plugin = entry.getKey();
if (entry.getValue() == null) {
continue;
}
// 拷贝数据,防止多线程问题
List<String> receivers = new ArrayList<>(entry.getValue());
// 此插件所有声明的 receiver
for (String receiver : receivers) {
try {
// 在对应进程接收广播, 如果进程未启动,则拉起之
int process = getProcessOfReceiver(plugin, receiver);
// todo 合并 IPluginClient 和 IPluginHost
if (process == IPluginManager.PROCESS_PERSIST) { //KP 如果是常驻进程,可直接调用onReceiver
IPluginHost host = PluginProcessMain.getPluginHost();
host.onReceive(plugin, receiver, intent);
} else {
IPluginClient client = MP.startPluginProcess(plugin, process, new PluginBinderInfo(PluginBinderInfo.NONE_REQUEST));
client.onReceive(plugin, receiver, intent); //KP 如果接收方不在常驻进程中,则需要进行IPC调用onReceive()
}
} catch (Throwable e) {
...
}
}
}
}
}
}

这个方法很好理解,就是根据action获取map>,然后如果插件进程还没启动就拉起它,之后调用IPluginClient.onReceive(),通过IPC调用到PluginProcessPer.onReceive():

1
2
3
public void onReceive(String plugin, final String receiver, final Intent intent) {
PluginReceiverHelper.onPluginReceiverReceived(plugin, receiver, mReceivers, intent);
}

可见这里只是起一个转接的作用,真正执行工作的是PluginReceiverHelper.onPluginReceiverReceived()方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* 插件静态注册的广播,从常驻代理到插件时,调用此方法
*/
public static void onPluginReceiverReceived(final String plugin,
final String receiverName,
final HashMap<String, BroadcastReceiver> receivers,
final Intent intent) {
if (TextUtils.isEmpty(plugin) || TextUtils.isEmpty(receiverName)) {
...
return;
}
// 使用插件的 Context 对象
final Context pContext = Factory.queryPluginContext(plugin);
if (pContext == null) {
return;
}
String key = String.format("%s-%s", plugin, receiverName);
BroadcastReceiver receiver = null;
if (receivers == null || !receivers.containsKey(key)) {
try {
// 使用插件的 ClassLoader 加载 BroadcastReceiver
Class c = loadClassSafety(pContext.getClassLoader(), receiverName);
if (c != null) {
receiver = (BroadcastReceiver) c.newInstance();
if (receivers != null) {
receivers.put(key, receiver);
}
...
}
} catch (Throwable e) {
...
}
} else {
receiver = receivers.get(key);
}
if (receiver != null) {
final BroadcastReceiver finalReceiver = receiver;
// 转到 ui 线程,因为这里是在Binder线程中
Tasks.post2UI(new Runnable() {
@Override
public void run() {
...
finalReceiver.onReceive(pContext, intent);
}
});
}
}

这个方法很简单,就是通过插件的PluginDexClassLoader加载相应的BroadcastReceiver子类,然后创建对象,最后在UI线程中调用其onReceive()方法。

可见,只要RePlugin框架完成了初始化,那么插件中的静态广播和独立App的静态广播效果是一样的,即同样有拉起进程的作用

2.插件中动态注册的BroadcastReceiver

2.1 更安全却不能IPC的LocalBroadcastManager

考虑到全局广播的安全隐患,Android系统之后推出了LocalBroadcastManager这个东东,它的接口也很简单,就是registerReceiver(BroadcastReceiver,IntentFilter), sendBroadcast(Intent), sendBroadcastSync(Intent), unregisterReceiver(BroadcastReceiver)方法。

下面我们就看看它的实现,首先是registerReceiver()方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Register a receive for any local broadcasts that match the given IntentFilter.
*
* @param receiver The BroadcastReceiver to handle the broadcast.
* @param filter Selects the Intent broadcasts to be received.
*
* @see #unregisterReceiver
*/
public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
synchronized (mReceivers) {
ReceiverRecord entry = new ReceiverRecord(filter, receiver);
ArrayList<IntentFilter> filters = mReceivers.get(receiver);
if (filters == null) {
filters = new ArrayList<IntentFilter>(1);
mReceivers.put(receiver, filters);
}
filters.add(filter);
for (int i=0; i<filter.countActions(); i++) {
String action = filter.getAction(i);
ArrayList<ReceiverRecord> entries = mActions.get(action);
if (entries == null) {
entries = new ArrayList<ReceiverRecord>(1);
mActions.put(action, entries);
}
entries.add(entry);
}
}
}

可见,这里就是利用mReceivers保存receiver和它的IntentFilter的关系,同时利用mActions保存action和ReceiverRecord的关系,看一下mReceivers和mActions的定义会更清楚:

1
2
3
4
private final HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers
= new HashMap<BroadcastReceiver, ArrayList<IntentFilter>>();
private final HashMap<String, ArrayList<ReceiverRecord>> mActions
= new HashMap<String, ArrayList<ReceiverRecord>>();

其中ReceiverRecord这个类的定义很简单:

1
2
3
4
5
6
7
8
9
10
11
private static class ReceiverRecord {
final IntentFilter filter;
final BroadcastReceiver receiver;
boolean broadcasting;
ReceiverRecord(IntentFilter _filter, BroadcastReceiver _receiver) {
filter = _filter;
receiver = _receiver;
}
...
}

非常简单的类,就是为了保存filter和receiver,不多说了。

而sendBroadcast()方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Broadcast the given intent to all interested BroadcastReceivers. This
* call is asynchronous; it returns immediately, and you will continue
* executing while the receivers are run.
*
* @param intent The Intent to broadcast; all receivers matching this
* Intent will receive the broadcast.
*
* @see #registerReceiver
*/
public boolean sendBroadcast(Intent intent) {
synchronized (mReceivers) {
final String action = intent.getAction();
final String type = intent.resolveTypeIfNeeded(
mAppContext.getContentResolver());
final Uri data = intent.getData();
final String scheme = intent.getScheme();
final Set<String> categories = intent.getCategories();
final boolean debug = DEBUG ||
((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
...
ArrayList<ReceiverRecord> entries = mActions.get(intent.getAction());
if (entries != null) {
if (debug) Log.v(TAG, "Action list: " + entries);
ArrayList<ReceiverRecord> receivers = null;
for (int i=0; i<entries.size(); i++) {
ReceiverRecord receiver = entries.get(i);
...
if (receiver.broadcasting) {
...
continue;
}
int match = receiver.filter.match(action, type, scheme, data,
categories, "LocalBroadcastManager");
if (match >= 0) {
...
if (receivers == null) {
receivers = new ArrayList<ReceiverRecord>();
}
receivers.add(receiver);
receiver.broadcasting = true;
} else {
if (debug) {
String reason;
switch (match) {
case IntentFilter.NO_MATCH_ACTION: reason = "action"; break;
case IntentFilter.NO_MATCH_CATEGORY: reason = "category"; break;
case IntentFilter.NO_MATCH_DATA: reason = "data"; break;
case IntentFilter.NO_MATCH_TYPE: reason = "type"; break;
default: reason = "unknown reason"; break;
}
Log.v(TAG, " Filter did not match: " + reason);
}
}
}
if (receivers != null) {
for (int i=0; i<receivers.size(); i++) {
receivers.get(i).broadcasting = false;
}
mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
}
return true;
}
}
}
return false;
}

这个方法虽然有点长,实际上逻辑很简单,就是就是根据action找到所有的ReceiverRecord(在ReceiverRecord中含有BroadcastReceiver和IntentFilter信息),然后调用IntentFilter的match()方法进行包含action, type, scheme, data, categories在内的匹配,如果能够匹配上,就记录在receivers(List对象)中,最后,将receivers信息保存在mPendingBroadcasts中,然后发现MSG_EXEC_PENDING_BROADCASTS到Handler中,而Handler中是这样处理的:

1
2
3
4
5
6
7
8
9
10
11
12
13
mHandler = new Handler(context.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_EXEC_PENDING_BROADCASTS:
executePendingBroadcasts();
break;
default:
super.handleMessage(msg);
}
}
};

而executePendingBroadcasts()方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private void executePendingBroadcasts() {
while (true) {
BroadcastRecord[] brs = null;
synchronized (mReceivers) {
final int N = mPendingBroadcasts.size();
if (N <= 0) {
return;
}
brs = new BroadcastRecord[N];
mPendingBroadcasts.toArray(brs);
mPendingBroadcasts.clear();
}
for (int i=0; i<brs.length; i++) {
BroadcastRecord br = brs[i];
for (int j=0; j<br.receivers.size(); j++) {
br.receivers.get(j).receiver.onReceive(mAppContext, br.intent);
}
}
}
}

这个方法很简单,就是遍历各个BroadcastReceiver然后逐个通知,可见LocalBroadcastReceiver确实更安全了,因为它只会在本进程中发送广播,但是使用其实也更受限制,即没有IPC能力

还有一个unregisterReceiver()方法,太简单了就不分析了。

2.2 replugin-plugin-gradle中对于LocalBroadcastManager做的替换

对于插件中LocalBroadcastManager的替换是在replugin-plugin-gradle中的LocalBroadcastInjector中的,它的injectClass()方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@Override
def injectClass(ClassPool pool, String dir, Map config) {
...
try {
// 不处理 LocalBroadcastManager.class
if (filePath.contains('android/support/v4/content/LocalBroadcastManager')) {
println "Ignore ${filePath}"
return super.visitFile(file, attrs)
}
stream = new FileInputStream(filePath)
ctCls = pool.makeClass(stream);
// println ctCls.name
if (ctCls.isFrozen()) {
ctCls.defrost()
}
/* 检查方法列表 */
ctCls.getDeclaredMethods().each {
it.instrument(editor)
}
ctCls.getMethods().each {
it.instrument(editor)
}
ctCls.writeFile(dir)
}
...
}
  • if (filePath.contains('android/support/v4/content/LocalBroadcastManager')),保护性逻辑,避免替换掉v4包中的源码实现。
  • pool.makeClass(),创建当前类文件的CtClass实例。
  • ctCls.defrost() 如果CtClass实例被冻结,则执行解冻操作。
  • ctCls.getDeclaredMethods().each { }ctCls.getMethods().each { },遍历全部方法,并执行instrument方法,逐个扫描每个方法体内每一行代码,并交由LocalBroadcastExprEditoredit()处理对方法体代码的修改

而LocalBroadcastExprEditor如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class LocalBroadcastExprEditor extends ExprEditor {
static def TARGET_CLASS = 'android.support.v4.content.LocalBroadcastManager'
static def PROXY_CLASS = 'com.qihoo360.replugin.loader.b.PluginLocalBroadcastManager'
/** 处理以下方法 */
static def includeMethodCall = ['getInstance',
'registerReceiver',
'unregisterReceiver',
'sendBroadcast',
'sendBroadcastSync']
...
@Override
void edit(MethodCall call) throws CannotCompileException {
if (call.getClassName().equalsIgnoreCase(TARGET_CLASS)) {
if (!(call.getMethodName() in includeMethodCall)) {
// println "Skip $methodName"
return
}
replaceStatement(call)
}
}
def private replaceStatement(MethodCall call) {
String method = call.getMethodName()
if (method == 'getInstance') {
call.replace('{$_ = ' + PROXY_CLASS + '.' + method + '($$);}')
} else {
def returnType = call.method.returnType.getName()
// getInstance 之外的调用,要增加一个参数,请参看 i-library 的 LocalBroadcastClient.java
if (returnType == 'void') {
call.replace('{' + PROXY_CLASS + '.' + method + '($0, $$);}')
} else {
call.replace('{$_ = ' + PROXY_CLASS + '.' + method + '($0, $$);}')
}
}
}
}

就是在replaceStatement()中完成了对于LocalBroadcastManager中getInstance(), registerReceiver(), unregisterReceiver(), sendBroadcast()和sendBroadSync()等方法的调用替换为PluginLocalBroadcastManager的调用。

2.3 PluginLocalBroadcastManager分析

PluginLocalBroadcastManager这个方法其实很简单,它甚至直接copy了LocalBroadcastManager的逻辑,对外的接口也是那几个方法,只是在RePluginFramework完成初始化之前,调用它copy的这个逻辑,在完成初始化之后,则是通过反射调用LocalBroadcastManager,不过真的不太明白这样做的意义在哪,不能从一开始就调用LocalBroadcastManager吗,或者说干脆一直就用这个逻辑不行吗?