前言
LocalBroadcastManager是从android.support.v4包中google后添加的,那肯定是为了解决原来的Broadcast的使用的方便,或者解决安全问题等等的考虑,Goole工程师才会专门来添加一个类来供我们使用。
那LocalBroadcastManager相比context发送的Broadcas到底有那些优点呢?
其中google的官方的API是这样解释的
/**
* Helper to register for and send broadcasts of Intents to local objects
* within your process. This has a number of advantages over sending
* global broadcasts with {@link android.content.Context#sendBroadcast}:
* <ul>
* <li> You know that the data you are broadcasting won't leave your app, so
* don't need to worry about leaking private data.
* <li> It is not possible for other applications to send these broadcasts to
* your app, so you don't need to worry about having security holes they can
* exploit.
* <li> It is more efficient than sending a global broadcast through the
* system.
* </ul>
*/
google的注释还是那么通俗易懂,那么贴心,翻译过来,它的有优点就有2条:
1.安全性:你正在发送广播的数据不会离开您的应用程序,所以不必担心泄漏私人数据,其他应用程序无法将这些广播发送到您的应用,因此您不必担心会有安全漏洞利用。通俗来说,就是你的广播其他应用没法收到,同样其他的应用也没法发相同的广播给你。
2.高效性:比全局广播更有效。
LocalBroadcastManager的实现原理?
构造函数
从源码中可以看出,LocalBroadcastManager内部是有一个单例的对象
public final class LocalBroadcastManager {
private static class ReceiverRecord {
//省略
}
private static class BroadcastRecord {
//省略
}
private static final String TAG = "LocalBroadcastManager";
private static final boolean DEBUG = false;
private final Context mAppContext;
private final HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers
= new HashMap<BroadcastReceiver, ArrayList<IntentFilter>>();
private final HashMap<String, ArrayList<ReceiverRecord>> mActions
= new HashMap<String, ArrayList<ReceiverRecord>>();
private final ArrayList<BroadcastRecord> mPendingBroadcasts
= new ArrayList<BroadcastRecord>();
static final int MSG_EXEC_PENDING_BROADCASTS = 1;
private final Handler mHandler;
private static final Object mLock = new Object();
private static LocalBroadcastManager mInstance;
//内部维护了一个单例的LocalBroadcastManager对象。
public static LocalBroadcastManager getInstance(Context context) {
synchronized (mLock) {
if (mInstance == null) {
mInstance = new LocalBroadcastManager(context.getApplicationContext());
}
return mInstance;
}
}
注册广播接收器
如果使用LocalBroadcastManager 注册一个广播
LocalBroadcastReceiver localReceiver = new LocalBroadcastReceiver();
LocalBroadcastManager.getInstance(context).registerReceiver(localReceiver, new IntentFilter(ACTION_LOCAL_SEND));
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 存储广播和过滤器信息,以BroadcastReceiver
作为 key,IntentFilter
链表作为 value。
mReceivers 是接收器和IntentFilter
的对应表,主要作用是方便在unregisterReceiver(…)
取消注册,同时作为对象锁限制注册接收器、发送广播、取消接收器注册等几个过程的并发访问。
mActions 以Action
为 key,注册这个Action
的BroadcastReceiver
链表为 value。mActions 的主要作用是方便在广播发送后快速得到可以接收它的BroadcastReceiver
。
发送广播
如果使用LocalBroadcastManager 发送一个广播
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(ACTION_LOCAL_SEND));
在发广播的时候,到底干了什么?
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);
if (debug) Log.v(
TAG, "Resolving type " + type + " scheme " + scheme
+ " of intent " + intent);
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 (debug) Log.v(TAG, "Matching against filter " + receiver.filter);
if (receiver.broadcasting) {
if (debug) {
Log.v(TAG, " Filter's target already added");
}
continue;
}
int match = receiver.filter.match(action, type, scheme, data,
categories, "LocalBroadcastManager");
if (match >= 0) {
if (debug) Log.v(TAG, " Filter matched! match=0x" +
Integer.toHexString(match));
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
从mActions
中取出ReceiverRecord
列表,循环每个ReceiverRecord
判断 filter 和 intent 中的 action、type、scheme、data、categoried 是否 match,是的话则保存到receivers
列表中,发送 what 为MSG_EXEC_PENDING_BROADCASTS
的消息,通过 Handler 去处理。
消息处理
mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS)发送消息
private LocalBroadcastManager(Context context) {
mAppContext = context;
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);
}
}
};
}
private void executePendingBroadcasts() {
//消息处理loop
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);
}
}
}
}
mPendingBroadcasts
转换为数组BroadcastRecord
,循环每个receiver
,调用其onReceive
函数,这样便完成了广播的核心逻辑
广播取消注册:
public void unregisterReceiver(BroadcastReceiver receiver) {
synchronized (mReceivers) {
ArrayList<IntentFilter> filters = mReceivers.remove(receiver);
if (filters == null) {
return;
}
for (int i=0; i<filters.size(); i++) {
IntentFilter filter = filters.get(i);
for (int j=0; j<filter.countActions(); j++) {
String action = filter.getAction(j);
ArrayList<ReceiverRecord> receivers = mActions.get(action);
if (receivers != null) {
for (int k=0; k<receivers.size(); k++) {
if (receivers.get(k).receiver == receiver) {
receivers.remove(k);
k--;
}
}
if (receivers.size() <= 0) {
mActions.remove(action);
}
}
}
}
}
}
遍历mReceivers
及mActions
中移除相应元素
总结:
1.LocalBroadcastManage其实内部是Handler 实现的应用内的通信,相比context的Broadcast依靠binder通信,自然安全性更好,效率更高。
2.从是实现角度来说,LocalBroadcastManage和context的Broadcast没有任何关系。其实可以理解为LocalBroadcastManage为了快速让开发者接受,借用了context的Broadcast的概念,这样让开发者更容易理解和使用。
最后:
context的Broadcast的安全问题是怎么解决的呢?
1.如果是静态注册添加属性android:exported="false"。
2.尽量不要使用广播发送敏感数据,如发送则需要限制好接受者的权限,或者通过显示意图、setPackage(String packageName)来指定接收器的包名。
3.在发送广播时指定接收者必须具备的permission。
最后最后:以上三条没卵用,只是相对安全。