LocalBroadcastManager源码分析
一、LocalBroadcastManager是什么
LocalBroadcastManager是Android Support包提供了一个工具,用于在同一个应用内的不同组件间发送Broadcast。LocalBroadcastManager也称为局部通知管理器,这种通知的好处是安全性高,效率也高,适合局部通信,可以用来代替Handler更新UI。
二、LocalBroadcastManager的优点
- 因广播数据在本应用范围内传播,你不用担心隐私数据泄露的问题。所以
LocalBroadcastManager
比BroadcastReceiver
更安全。 - 不用担心别的应用伪造广播,造成安全隐患。
- 相比在系统内发送全局广播,它更高效。
三、LocalBroadcastManager使用
- 获取LocalBroadcastManager实例
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(ctx);
- 注册,需要传入BroadcastReceiver和IntentFilter对象
localBroadcastManager.registerReceiver(receiver, filter);
- 发送,需传入一个Intenet对象
localBroadcastManager.sendBroadcast(intent);
- 注销,需要通过创建的BroadcastReceiver对象来实现注销
localBroadcastManager.unregisterReceiver(receiver);
四、LocalBroadcastManager使用小例子
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/local_textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="LocalBroadcastReciver"
android:textColor="@android:color/holo_orange_light"
android:textSize="20sp" />
</LinearLayout>
public class LocalBroadcastReciverAct extends AppCompatActivity {
private LocalBroadcastManager localBroadcastManager = null;
private BroadcastReceiver broadcastReceiver = null;
private IntentFilter intentFilter = null;
private static final String ACTION = "LOCAL_BROADCAST_RECIVER_ACTION";
private TextView localTextview = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_local_broadcast_reciver);
localTextview = findViewById(R.id.local_textview);
localTextview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
localBroadcastManager.sendBroadcast(new Intent(ACTION));
}
});
localBroadcastManager = LocalBroadcastManager.getInstance(this);
}
@Override
protected void onStart() {
super.onStart();
initReciverFilter();
localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
}
private void initReciverFilter() {
broadcastReceiver = new MyBroadcastReciver();
intentFilter = new IntentFilter(ACTION);
}
@Override
protected void onStop() {
super.onStop();
localBroadcastManager.unregisterReceiver(broadcastReceiver);
}
private class MyBroadcastReciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
localTextview.setText("已接受到LocalBroadcastReciver");
}
}
}
效果图
五、源码分析
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(ctx);
private final Handler mHandler;
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;
}
}
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);
}
}
};
}
从构造方法私有化,很明显这是一个单利模式,并且进行了加锁操作所以是一个线程安全的单利模式;并且在LocalBroadcastManager
的构造方法中我们看见了mHandler = new Handler(context.getMainLooper())
,所以可以初步断定LocalBroadcastManager
是通过handler+message实现的消息广播,context.getMainLooper()
是主线程的Looper,所以这个handler是运行在主线程的,不能进行耗时操作!
localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
// 广播接收器作为key,接收器记录集合作为value
private final HashMap<BroadcastReceiver, ArrayList<ReceiverRecord>> mReceivers = new HashMap<>();
// 筛选动作(类型)作为key,接收器记录集合作为value
private final HashMap<String, ArrayList<ReceiverRecord>> mActions = new HashMap<>();
public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
synchronized (mReceivers) {
ReceiverRecord entry = new ReceiverRecord(filter, receiver);
ArrayList<ReceiverRecord> filters = mReceivers.get(receiver);
if (filters == null) {
filters = new ArrayList<>(1);
mReceivers.put(receiver, filters);
}
filters.add(entry);
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);
}
}
}
registerReceiver
只是做了一些数据的分类保存操作。ReceiverRecord
是一个内部类,主要是存储广播接收器BroadcastReceiver
,筛选器IntentFilter
,及广播运行状态。
private static final class ReceiverRecord {
final IntentFilter filter; // 筛选器
final BroadcastReceiver receiver; // 广播接收器
boolean broadcasting; // 是否处于激活状态
boolean dead; // 广播是否已经销毁
............
}
private static final String ACTION = "LOCAL_BROADCAST_RECIVER_ACTION";
localBroadcastManager.sendBroadcast(new Intent(ACTION));
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;
// 遍历集合,找到符合条件的ReceiverRecord
for (int i=0; i<entries.size(); i++) {
ReceiverRecord receiver = entries.get(i);
if (debug) Log.v(TAG, "Matching against filter " + receiver.filter);
// 已经处于激活状态的ReceiverRecord过滤掉(主要避免重复加入)
if (receiver.broadcasting) {
if (debug) {
Log.v(TAG, " Filter's target already added");
}
continue;
}
// 判断本次循环取出的ReceiverRecord,在动作、数据,分类是否匹配
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); // 符合条件的加入到receivers中
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; // 筛选完后,将状态重置
}
// 重新构造一个BroadcastRecord对象,并添加到待发送状态下的广播列表
mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
// 查看handler在排队执行的消息中是否有MSG_EXEC_PENDING_BROADCASTS类型,
// 没有,添加一个MSG_EXEC_PENDING_BROADCASTS类型的消息
if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
}
return true;
}
}
}
return false;
}
sendBroadcast()
中主要进行的是广播接受器的筛选操作,然后通知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 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<brs.length; i++) {
final BroadcastRecord br = brs[i];
final int nbr = br.receivers.size();
// 遍历调用接收器方法
for (int j=0; j<nbr; j++) {
final ReceiverRecord rec = br.receivers.get(j);
// 不在销毁状态下,调用接收器的onReceive()方法执行
if (!rec.dead) {
rec.receiver.onReceive(mAppContext, br.intent);
}
}
}
}
}
executePendingBroadcasts()
执行接收器的onReceive()
方法。
localBroadcastManager.unregisterReceiver(broadcastReceiver);
public void unregisterReceiver(BroadcastReceiver receiver) {
synchronized (mReceivers) {
// 从mReceivers中移除,并返回对应的记录集合
final ArrayList<ReceiverRecord> filters = mReceivers.remove(receiver);
if (filters == null) {
return;
}
// 遍历接收器记录集合,并设置dead = true; 避免正在运行的executePendingBroadcasts()执行此接收器的回调
for (int i=filters.size()-1; i>=0; i--) {
final ReceiverRecord filter = filters.get(i);
filter.dead = true;
for (int j=0; j<filter.filter.countActions(); j++) {
final String action = filter.filter.getAction(j);
final ArrayList<ReceiverRecord> receivers = mActions.get(action);
if (receivers != null) {
for (int k=receivers.size()-1; k>=0; k--) {
final ReceiverRecord rec = receivers.get(k);
if (rec.receiver == receiver) {
rec.dead = true;
receivers.remove(k);
}
}
if (receivers.size() <= 0) {
mActions.remove(action);
}
}
}
}
}
}
unregisterReceiver()
中主要是资源的释放,并将注册的BroadcastReceiver
相关信息,从集合中删除,并设置BroadcastReceiver
对应的ReceiverRecord
的dead
状态标记为true
,避免被执行。
六、总结
LocalBroadcastManager的内部是通过handler来实现广播消息的分发,这样的广播只能在本应用内分发,所以不必担心安全问题,因为别人根本够不到你~~