用法:
// 在onCreate中注册 LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,intentFilter)
// 在onDestroy中解除注册 LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver)
// 进行广播 LocalBroadcastManager.getInstance(this).sendBroadcast(Intent(ACTION))
可以看到跟系统广播用法完全一致,那么二者内部有何不同呢?
源码解析:
1,内部类
//该类很简单,顾名思义是接收者记录,将接收者和过滤器绑定
private static final class ReceiverRecord {
final IntentFilter filter;
final BroadcastReceiver receiver;
boolean broadcasting;//标识已收到广播但还未添加到待处理队列中
boolean dead;//只有取消注册该记录才会死亡
//省略了构造方法和toString方法
}
//该类很简单,顾名思义是广播记录,将广播和多个接收者记录绑定
private static final class BroadcastRecord {
final Intent intent;
final ArrayList
receivers; }
2,主要成员变量
//以接收者为key,以接收者记录列表为value
//因为一个接收者可以被注册多次,所以value为一个列表
private final HashMap
> mReceivers = new HashMap<>(); //以广播的Action为key,以接收者记录列表为value;Action是所有注册过的过滤器要过滤的Action
//如此收到广播后可立即获取监听该Action的所有接收者
private final HashMap
> mActions = new HashMap<>(); //广播记录列表,每个广播记录里存储了该广播和接受该广播的接收者,用于handler挨个执行onReceive方法
private final ArrayList
mPendingBroadcasts = new ArrayList<>();
3,主要方法
private final Handler mHandler;
//构造方法私有,初始化handler;可以看到handler内部很简单
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 static final Object mLock = new Object();
private static LocalBroadcastManager mInstance;
//实例化方法,通用的单例模式;
//还有一种效率更高的双重判断的单例模式:在synchronized外先判空一下,若已实例化就不用获取锁了;
//广播一般不会用于多线程,所以不加也没太大损失
public static LocalBroadcastManager getInstance(Context context) {
synchronized (mLock) {
if (mInstance == null) {
mInstance = new LocalBroadcastManager(context.getApplicationContext());
}
return mInstance;
}
}
//注册广播
public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
//以接收者记录列表为锁,防止遍历期间在其他线程进行注册
synchronized (mReceivers) {
ReceiverRecord entry = new ReceiverRecord(filter, receiver);//绑定接收者和过滤器
ArrayList
filters = mReceivers.get(receiver); if (filters == null) {
filters = new ArrayList<>(1);
mReceivers.put(receiver, filters);
}
filters.add(entry);//相当于以接收者为key存储了该接收者对应的过滤器
for (int i=0; i
String action = filter.getAction(i);
ArrayList
entries = mActions.get(action); if (entries == null) {
entries = new ArrayList
(1); mActions.put(action, entries);
}
entries.add(entry);
}
}
}
//发送广播
public boolean sendBroadcast(Intent intent) {
//以接收者记录列表为锁,防止遍历期间在其他线程进行广播
synchronized (mReceivers) {
//解析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
categories = intent.getCategories(); ......
//获取注册了该action的所有接收者记录
ArrayList
entries = mActions.get(intent.getAction()); if (entries != null) {
......
//准备获取所有完全匹配该Intent的接收者
ArrayList
receivers = null; for (int i=0; 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
(); }
//若匹配则先记录该接收者,并将标记其已经知道广播来了
receivers.add(receiver);
receiver.broadcasting = true;
} else {
// debug相关代码
......
}
}
if (receivers != null) {
//每个接收者复位,表示可以继续接受新的广播;随后所有匹配的接收者会放入队列,等待处理已接收的广播
for (int i=0; i
receivers.get(i).broadcasting = false;
}
//所有匹配的接收者放入队列,等待处理已接收的广播
mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
//如果handler正在处理广播队列,那么就不用发了,因为添加到队列末尾最终肯定会被执行
if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
}
return true;
}
}
}
return false;
}
//处理广播队列,真正执行逻辑的地方
private void executePendingBroadcasts() {
while (true) {//这里不对广播队列进行遍历,因为下方可以看到其他线程是可以调用该方法的,处理过程中可能还有新的广播记录加入队列
final BroadcastRecord[] brs;
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
final BroadcastRecord br = brs[i];
final int nbr = br.receivers.size();
for (int j=0; j
final ReceiverRecord rec = br.receivers.get(j);
if (!rec.dead) {//若没有取消注册,则执行
rec.receiver.onReceive(mAppContext, br.intent);
}
}
}
}
}
//取消注册
public void unregisterReceiver(BroadcastReceiver receiver) {
//以接收者记录列表为锁,防止遍历期间在其他线程进行解除注册
synchronized (mReceivers) {
final ArrayList
filters = mReceivers.remove(receiver); if (filters == null) {
return;
}
//一个接收者可能有多个过滤器,而一个过滤器可能过滤多个action,所以有多重循环
for (int i=filters.size()-1; i>=0; i--) {//遍历该接受者对应的所有过滤器
final ReceiverRecord filter = filters.get(i);
filter.dead = true;//该记录死亡
for (int j=0; j
final String action = filter.filter.getAction(j);
final ArrayList
receivers = mActions.get(action); if (receivers != null) {
for (int k=receivers.size()-1; k>=0; k--) {//遍历该action存储的所有接收者
final ReceiverRecord rec = receivers.get(k);
if (rec.receiver == receiver) {
rec.dead = true;//该记录死亡
receivers.remove(k);//该action不再对应该接收者
}
}
if (receivers.size() <= 0) {//若没有接收者监听该action了,则移除该action
mActions.remove(action);
}
}
}
}
}
}
//类似普通的发送广播,但在该方法执行完时,注册过该广播的接收者必定处理完该广播了
//等于提供了额外的选择,在广播执行完毕后再做其他事
public void sendBroadcastSync(Intent intent) {
if (sendBroadcast(intent)) {
executePendingBroadcasts();
}
}