前言:
在Android中,Broadcast是一种广泛运用的在应用程序之间传输信息的机制。BroadcastReceiver设计的
初衷是从全局考虑可以方便应用程序和系统、应用程序之间、应用程序内的通信。但是有时候只是给进程
内部发送广播也需要绕一大圈,有没有简单的方法呢? LocalBroadcastManager。
LocalBroadcastManager是Android Support包提供了一个工具,用于在同一个应用内的不同组件间发送
Broadcast。LocalBroadcastManager也称为局部通知管理器,这种通知的好处是安全性高,效率也高,
适合局部通信,可以用来代替Handler更新UI。
LocalBroadcastManager使用也很简单,四个步骤如下,
1,获取LocalBroadcastManager对象,
LocalBroadcastManager mlocalBroadcastManager = LocalBroadcastManager.getInstance( this ) ;
2, 注册广播接收器
mlocalBroadcastManager.registerReceiver( broadcastReceiver , intentFilter );
3, 发送广播
mlocalBroadcastManager.sendBroadcast( intent ) ;
4, 取消注册广播接收器
mlocalBroadcastManager.unregisterReceiver( broadcastReceiver );
LocalBroadcastManager的全局变量如下,
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;//单例
mReceivers:记录注册的BroadcastReceiver及其IntentFilter的数组。
mActions:记录IntentFilter中的action对应的BroadcastReceiver数组。虽然这里写的是ReceiverRecord类型,
但它实际上是一个内部类,主要保存了BroadcastReceiver及其对应的IntentFilter。
mPendingBroadcasts:在发送广播时,会根据Intent的action,找到与之相对应的BroadcastReceiver。action
是可以对应多个BroadcastReceiver,所以这里是数组。
1, getInstance分析
LocalBroadcastManager是一个单例,代码如下,
public static LocalBroadcastManager getInstance(Context context) {
synchronized (mLock) {
if (mInstance == null) {
mInstance = new LocalBroadcastManager(context.getApplicationContext());
}
return mInstance;
}
}
其构造方法如下,
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);
}
}
};
}
构造了一个Handler对象,并且该mHandler仅处理一个消息。
2, registerReceiver分析
LocalBroadcastManager的registerReceiver方法如下,
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);
}
}
}
将BroadcastReceiver和IntentFilter建立一对多的对应关系。可以通过BroadcastReceiver找到其对应的IntentFilter,
也可以通过IntentFilter中的action找到所对应的BroadcastReceiver。
3, unregisterReceiver分析
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);
}
}
}
}
}
}
和注册的过程完全相反, 将BroadcastReceiver从mReceivers和mActions中移除掉。由于BroadcastReceiver是mReceivers的键,
所以移除掉比较简单。而mActions就稍微复杂一些,需要根据BroadcastReceiver中的IntentFilter数组,从mActions中移除掉。
4 sendBroadcast分析
sendBroadcast主要逻辑如下,
1,首先获取intent的参数信息,
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();
2, 从mActions中取出intent的action所对应的ReceiverRecord,逐个匹配
ArrayList<ReceiverRecord> entries = mActions.get(intent.getAction());
•••
ArrayList<ReceiverRecord> receivers = null;
for (int i=0; i<entries.size(); i++) {
•••
//进行匹配
int match = receiver.filter.match(action, type, scheme, data, categories, "LocalBroadcastManager");
receivers.add(receiver);//如果匹配上,添加到receivers中
receiver.broadcasting = true;//将匹配上的状态置为发送中
3,最后将匹配的receivers添加到mPendingBroadcasts中,然后发送MSG_EXEC_PENDING_BROADCASTS消息,
实际上是切换到主线程执行。
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;
}
mHandler收到MSG_EXEC_PENDING_BROADCASTS消息后,调用executePendingBroadcasts方法进行处理,
executePendingBroadcasts()方法就很简单了,就是取出mPendingBroadcasts数组中的BroadcastReceiver
(在ReceiverRecord中保存其对象),调用其onReceive方法。
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);
}
}
}
}
小结:
1,BroadcastReceiver的通信是走 Binder 机制,所以可以跨进程通信;但是LocalBroadcastManager是handler机制,
所以只能进行进程内部通信。并且, LocalBroadcastManager都是动态注册的, 如果广播仅经过LocalBroadcastManager注册,
也只能收到LocalBroadcastManager sendBroadcast的广播。BroadcastReceiver和LocalBroadcastManager不要混为一团。
2, LocalBroadcastManager仅适用于进程内的广播。
3,优点: 发送的广播只会在当前APP中传播,不会泄露给其它APP,确保了数据传输的安全。其它APP的广播无法发送到
本APP中,不用担心安全漏洞被其它APP所利用。比系统全局广播更加高效。