- 是什么,有什么優(yōu)勢(shì)葱淳?
* 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>
*/
簡(jiǎn)單來(lái)說(shuō)就是:本地的廣播
優(yōu)勢(shì):
- 發(fā)送廣播的角度來(lái)說(shuō):廣播的數(shù)據(jù)局限在本app內(nèi)沮协,無(wú)需擔(dān)心數(shù)據(jù)泄露;
- 接收廣播的角度來(lái)說(shuō):其他應(yīng)用的廣播不可能會(huì)被本app接收到啦辐,因此無(wú)需擔(dān)心因此產(chǎn)生的安全漏洞谓传;
2.如何使用? 單例模式
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver,intentFilter);
LocalBroadcastManager.getInstance(this).sendBroadcastSync(intent);
可見(jiàn):是采用單例模式來(lái)實(shí)現(xiàn)的芹关,看下實(shí)現(xiàn)機(jī)制:
private static final Object mLock = new Object(); //保持可見(jiàn)性
private static LocalBroadcastManager mInstance;
public static LocalBroadcastManager getInstance(Context context) {
synchronized (mLock) {
if (mInstance == null) {
mInstance = new LocalBroadcastManager(context.getApplicationContext());
}
return mInstance;
}
}
采取的雙重鎖的單例實(shí)現(xiàn)形式续挟;
- 重要方法和變量
三大方法:注冊(cè),解注冊(cè)侥衬,發(fā)送廣播
三大變量: mReceivers mActions mPendingBroadcasts
一大核心:handler
- Handler來(lái)進(jìn)行分發(fā)
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);
}
}
};
可見(jiàn):handler是綁定在主線程的looper的诗祸,executePendingBroadcasts()稍后再看
- 三大變量:
//記錄監(jiān)聽(tīng)器和他的過(guò)濾原則的映射,注冊(cè)時(shí)使用
private final HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers
= new HashMap<BroadcastReceiver, ArrayList<IntentFilter>>();
//記錄 action和 相關(guān)的監(jiān)聽(tīng)器包裝類(lèi)的映射浇冰,查找時(shí)使用贬媒,(作用是方便查找)
private final HashMap<String, ArrayList<ReceiverRecord>> mActions
= new HashMap<String, ArrayList<ReceiverRecord>>();
//符合規(guī)則的監(jiān)聽(tīng)器,待一一通知接收消息
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;
}
- 三大方法
注冊(cè)監(jiān)聽(tīng): 分別添加到 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);
}
}
}
解注冊(cè): 刪除對(duì)應(yīng)的 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++) {
//列表刪除肘习;注意下標(biāo)編號(hào)
if (receivers.get(k).receiver == receiver) {
receivers.remove(k);
k--;
}
}
//<食恕!
if (receivers.size() <= 0) {
mActions.remove(action);
}
}
}
}
}
}
發(fā)送廣播: 找到符合規(guī)律的廣播漂佩,并添加到mPendingBroadcasts中脖含,并通過(guò)handler向looper發(fā)消息
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);
//這個(gè)標(biāo)志位什么情況下會(huì)用得到?還請(qǐng)指點(diǎn)下投蝉?
if (receiver.broadcasting) {
if (debug) {
Log.v(TAG, " Filter's target already added");
}
continue;
}
// 過(guò)濾出 合適的監(jiān)聽(tīng)器
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>();
}
// 合適的監(jiān)聽(tīng)器添加到集合中
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) {
//統(tǒng)一清除標(biāo)志养葵,
for (int i=0; i<receivers.size(); i++) {
receivers.get(i).broadcasting = false;
}
mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
//消息隊(duì)列中沒(méi)有此消息,才發(fā)生
if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
}
// 重要瘩缆!
return true;
}
}
}
return false;
}
可見(jiàn):就做了兩個(gè)工作关拒,1. 過(guò)濾出合適的監(jiān)聽(tīng)器; 2. 把監(jiān)聽(tīng)器放到集合里,并通過(guò)handler發(fā)送消息(如果已經(jīng)有消息了着绊,則不發(fā)送谐算,但沒(méi)關(guān)系,畢竟監(jiān)聽(tīng)器已添加到集合里了)
- 怎么處理消息
這部分單獨(dú)拿出來(lái)归露,是因?yàn)橛?個(gè)內(nèi)容: 通知監(jiān)聽(tīng)器 同步異步廣播的區(qū)別
- 通知監(jiān)聽(tīng)器
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();
}
// 一 一通知監(jiān)聽(tīng)器
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);
}
}
}
}
- 同步異步廣播
//同步廣播:可見(jiàn)洲脂,他并不通過(guò)handler來(lái)通知消息,而是立即執(zhí)行
public void sendBroadcastSync(Intent intent) {
if (sendBroadcast(intent)) {
executePendingBroadcasts();
}
}
因此可總結(jié)同步和異步發(fā)送廣播的區(qū)別:
- 異步廣播是通過(guò)handler發(fā)送消息剧包,在主線程的looper中排隊(duì)執(zhí)行恐锦,因此并不是立刻執(zhí)行的,但因?yàn)橛衕andler機(jī)制疆液,異步廣播可在子線程中發(fā)送一铅;
- 同步廣播是立即執(zhí)行的,無(wú)需等待堕油;但必須在主線程中發(fā)送馅闽,否則違反安卓的單線程安全機(jī)制會(huì)引發(fā)奔潰;
本地廣播和全局廣播的區(qū)別:
本地廣播:效率更高馍迄,但不能夠跨進(jìn)程傳播;
全局廣播:安全性不能保證
本地廣播基本結(jié)束局骤,只要符合場(chǎng)景的攀圈,我們就用起來(lái)吧~~