- 是什么,有什么优势?
* 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>
*/
简单来说就是:本地的广播
优势:
- 发送广播的角度来说:广播的数据局限在本app内,无需担心数据泄露;
- 接收广播的角度来说:其他应用的广播不可能会被本app接收到,因此无需担心因此产生的安全漏洞;
2.如何使用? 单例模式
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver,intentFilter);
LocalBroadcastManager.getInstance(this).sendBroadcastSync(intent);
可见:是采用单例模式来实现的,看下实现机制:
private static final Object mLock = new Object(); //保持可见性
private static LocalBroadcastManager mInstance;
public static LocalBroadcastManager getInstance(Context context) {
synchronized (mLock) {
if (mInstance == null) {
mInstance = new LocalBroadcastManager(context.getApplicationContext());
}
return mInstance;
}
}
采取的双重锁的单例实现形式;
- 重要方法和变量
三大方法:注册,解注册,发送广播
三大变量: mReceivers mActions mPendingBroadcasts
一大核心:handler
- Handler来进行分发
static final int MSG_EXEC_PENDING_BROADCASTS = 1;
private final Handler mHandler;
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是绑定在主线程的looper的,executePendingBroadcasts()稍后再看
- 三大变量:
//记录监听器和他的过滤原则的映射,注册时使用
private final HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers
= new HashMap<BroadcastReceiver, ArrayList<IntentFilter>>();
//记录 action和 相关的监听器包装类的映射,查找时使用,(作用是方便查找)
private final HashMap<String, ArrayList<ReceiverRecord>> mActions
= new HashMap<String, ArrayList<ReceiverRecord>>();
//符合规则的监听器,待一一通知接收消息
private final ArrayList<BroadcastRecord> mPendingBroadcasts
= new ArrayList<BroadcastRecord>();
其中:
private static class ReceiverRecord {
final IntentFilter filter;
final BroadcastReceiver receiver;
boolean broadcasting;
}
private static class BroadcastRecord {
final Intent intent;
final ArrayList<ReceiverRecord> receivers;
}
- 三大方法
注册监听: 分别添加到 mReceivers mActions
public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
synchronized (mReceivers) {
ReceiverRecord entry = new ReceiverRecord(filter, receiver);
//添加到mReceivers
ArrayList<IntentFilter> filters = mReceivers.get(receiver);
if (filters == null) {
filters = new ArrayList<IntentFilter>(1);
mReceivers.put(receiver, filters);
}
filters.add(filter);
//添加到mActions
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 mActions
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);
}
}
}
}
}
}
发送广播: 找到符合规律的广播,并添加到mPendingBroadcasts中,并通过handler向looper发消息
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;
}
可见:就做了两个工作,1. 过滤出合适的监听器; 2. 把监听器放到集合里,并通过handler发送消息(如果已经有消息了,则不发送,但没关系,毕竟监听器已添加到集合里了)
- 怎么处理消息
这部分单独拿出来,是因为有2个内容: 通知监听器 同步异步广播的区别
- 通知监听器
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);
}
}
}
}
- 同步异步广播
//同步广播:可见,他并不通过handler来通知消息,而是立即执行
public void sendBroadcastSync(Intent intent) {
if (sendBroadcast(intent)) {
executePendingBroadcasts();
}
}
因此可总结同步和异步发送广播的区别:
- 异步广播是通过handler发送消息,在主线程的looper中排队执行,因此并不是立刻执行的,但因为有handler机制,异步广播可在子线程中发送;
- 同步广播是立即执行的,无需等待;但必须在主线程中发送,否则违反安卓的单线程安全机制会引发奔溃;
本地广播和全局广播的区别:
本地广播:效率更高,但不能够跨进程传播;
全局广播:安全性不能保证
本地广播基本结束,只要符合场景的,我们就用起来吧~~