背景
廣播作為Android 四大組件有非常廣泛的用途占拍。廣播可以用作進(jìn)程間通信沽讹,也會(huì)用作進(jìn)程內(nèi)部某些組件內(nèi)消息的傳遞宾符。
這就會(huì)有個(gè)問(wèn)題佛南,如果想讓發(fā)送的廣播只有我自己能收到梗掰,不想被別人劫持到,來(lái)獲取到廣播中的敏感信息嗅回。
另外其他人如果發(fā)送相同Action的廣播來(lái)偽造真正的廣播及穗,就會(huì)欺騙我的receiver.
如何安全高效的實(shí)現(xiàn)進(jìn)程內(nèi)部的廣播發(fā)送呢?
有人說(shuō)可以使用給廣播加權(quán)限啊绵载,你可以在Intent中指定PackageName 啊埂陆,后面的文章詳解苛白,先簡(jiǎn)單看下:
當(dāng)應(yīng)用程序發(fā)送某個(gè)廣播時(shí)系統(tǒng)會(huì)將發(fā)送的Intent與系統(tǒng)中所有注冊(cè)的BroadcastReceiver的IntentFilter進(jìn)行匹配,若匹配成功則執(zhí)行相應(yīng)的onReceive函數(shù)焚虱」喝梗可以通過(guò)類似sendBroadcast(Intent,String)的接口在發(fā)送廣播時(shí)指定接收者必須具備的permission【樵裕或通過(guò)Intent.setPackage設(shè)置廣播僅對(duì)某個(gè)程序有效躏率。
當(dāng)應(yīng)用程序注冊(cè)了某個(gè)廣播時(shí),即便設(shè)置了IntentFilter還是會(huì)接收到來(lái)自其他應(yīng)用程序的廣播進(jìn)行匹配判斷谍咆。對(duì)于動(dòng)態(tài)注冊(cè)的廣播可以通過(guò)類似registerReceiver(BroadcastReceiver,IntentFilter,String,android.os.Handler)的接口指定發(fā)送者必須具備的permission禾锤,對(duì)于靜態(tài)注冊(cè)的廣播可以通過(guò)android:exported="false"屬性表示接收者對(duì)外部應(yīng)用程序不可用,即不接受來(lái)自外部的廣播摹察。
當(dāng)然這都是書(shū)上告訴我們的方式恩掷,但是我感覺(jué)還不夠簡(jiǎn)單。當(dāng)然經(jīng)過(guò)一番配置你可以實(shí)現(xiàn)了供嚎。
好了黄娘,現(xiàn)在安全解決了,那高效呢克滴?
我們翻看context.sendBroadcast源碼逼争,看到發(fā)送廣播的流程真的是相當(dāng)?shù)膹?fù)雜啊。曾經(jīng)天真年少的我竟然幻想一天弄懂廣播的整個(gè)過(guò)程劝赔,但當(dāng)我看到sendBroadcast方法的行數(shù)時(shí)我臉上是大寫(xiě)的崩潰誓焦。暫且不談廣播隊(duì)列的分發(fā)規(guī)則和過(guò)程。這中間是存在的兩次binder call就讓這個(gè)過(guò)程變的不是那么高效着帽。
首先你sendBroadcast會(huì)把廣播信息告訴System_server (第一次Binder call),然后system_server經(jīng)過(guò)一番查看找到你要的receivers,然后進(jìn)入分發(fā)隊(duì)列等待分發(fā)(過(guò)程很復(fù)雜)杂伟,然后調(diào)用APP進(jìn)程receiver的onReceiver()方法(第二次Binder call).大兄弟,我明明只想在我的進(jìn)程內(nèi)部發(fā)送一個(gè)廣播在進(jìn)程內(nèi)部接收仍翰,為啥還要通過(guò)system_server呢赫粥。就算你長(zhǎng)得帥,你有Free style,可是你很忙啊予借,找你的人那么多越平。自己的事情自己做,這是小學(xué)了老師經(jīng)常教導(dǎo)我們的灵迫∏嘏眩看來(lái)Google的程序員一直沒(méi)有忘記小學(xué)老師的教誨:
簡(jiǎn)介
看,邁著整齊步伐雄赳赳氣昂昂向我們走來(lái)的是LocalBroadcast:
先來(lái)看官方說(shuō)明:
**
- Helper to register for and send broadcasts of Intents to local objects
- within your process. This is 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>
*/
意思就是這個(gè)很牛逼瀑粥,和全局廣播相比有很多數(shù)不清的優(yōu)勢(shì)挣跋。(看來(lái)實(shí)現(xiàn)這個(gè)的哥們和實(shí)現(xiàn)全局廣播的哥們關(guān)系不大好,竟然用這個(gè)詞語(yǔ): has a number of advantages) 利凑。
- 廣播中攜帶的數(shù)據(jù)只會(huì)在你的APP中浆劲,不會(huì)暴露給其他APP,所以不用擔(dān)心數(shù)據(jù)泄露的問(wèn)題哀澈。
- 其他APP無(wú)法偽造廣播來(lái)欺騙你的Receiver
源碼分析
我們下面來(lái)看下LocalBroadcastManager的源碼:
https://android.googlesource.com/platform/frameworks/support/+/android-support-lib-19.1.0/v4/java/android/support/v4/content/LocalBroadcastManager.java
1.先來(lái)看下LocalBroadcastManager的構(gòu)造牌借,是使用標(biāo)準(zhǔn)的單例模式實(shí)現(xiàn)的。
APP開(kāi)發(fā)者拿到mInstance之后就可以調(diào)用registerReceiver割按、unregisterReceiver膨报、sendBroadcast。
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);
}
}
};
}
看到構(gòu)造函數(shù)中沒(méi)有做復(fù)雜的操作适荣,在主線程初始化了一個(gè)Handler.
可以猜測(cè)到這個(gè)Handler正是用于對(duì)廣播的分發(fā)现柠。
2.廣播的注冊(cè)、反注冊(cè)弛矛、發(fā)送流程
如果讓我們來(lái)自己來(lái)實(shí)現(xiàn)廣播的注冊(cè)够吩、反注冊(cè)、發(fā)送我們會(huì)怎么搞呢丈氓?
首先周循,注冊(cè)的時(shí)候需要提供BroadcastReceiver和對(duì)應(yīng)的IntentFilter,我們可以對(duì)這種數(shù)據(jù)結(jié)構(gòu)進(jìn)行封裝,放到一個(gè)類中ReceiverRecord万俗。
然后維護(hù)一個(gè)ReceiverRecord對(duì)象列表湾笛,用于記錄當(dāng)前注冊(cè)了哪些BroadcastReceiver∪蛲幔可以簡(jiǎn)單使用ArrayList<ReceiverRecord>.
在unRegister的時(shí)候根據(jù)提供的BroadcastReceiver對(duì)象,遍歷List找出對(duì)應(yīng)的receiver進(jìn)行移除嚎研。
這樣每來(lái)一個(gè)unRegister我們都需要對(duì)Receiver列表做一次遍歷,開(kāi)銷有點(diǎn)大库倘,在查操作比較多的時(shí)候我們可以使用MAP临扮。
HashMap<BroadCastReceiver, ReceiverRecord>
ReceiverRecord中已經(jīng)包含BroadcastReceiver對(duì)象了,所以value直接使用IntentFilte就行了于樟,簡(jiǎn)化數(shù)據(jù)結(jié)構(gòu)公条。
那如果一個(gè)Receiver注冊(cè)了多個(gè)IntentFilter呢?比如說(shuō)一個(gè)receiver對(duì)象注冊(cè)兩次傳入不同的IntentFilter.所以Value需要改造為ArrayList<IntentFilter>迂曲。 最終用于維護(hù)當(dāng)前Reciver對(duì)象列表的數(shù)據(jù)結(jié)構(gòu)是這樣事兒的:
HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers
.
當(dāng)刪除時(shí)可以通過(guò)receiver對(duì)象為key在map中快速查找并移除靶橱。
發(fā)送廣播的時(shí)候呢?我們知道sendBroadcast時(shí)只傳入了Intent對(duì)象路捧,Intent攜帶了Action用于和已經(jīng)注冊(cè)的receiver匹配关霸。在查找receiver時(shí),需要對(duì)HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers
的Value進(jìn)行遍歷杰扫,每一個(gè)Value ArrayList<IntentFilter> 又需要遍歷一次队寇。這個(gè)查找的開(kāi)銷實(shí)在太大了。
看來(lái)我們?yōu)榱藢?shí)現(xiàn)Action和receiver的快速匹配需要再維護(hù)一個(gè)數(shù)據(jù)結(jié)構(gòu)了章姓。同樣是頻繁查找的需求使用HashMap.
將Action作為Key,value肯定是與之匹配的receiver了佳遣。因?yàn)橐粋€(gè)Action可能會(huì)對(duì)應(yīng)多個(gè)receiver,receiver注冊(cè)的時(shí)候可以使用相同的Action.所以value需要使用ArrayList<BroadcastReceiver>. 當(dāng)發(fā)送廣播時(shí)可以快速根據(jù)Action找到對(duì)應(yīng)的receiver识埋。對(duì)了,不僅僅要使用Action匹配零渐,filter中還有其他信息匹配成功之后才能確認(rèn)是真正的receiver.所以需要使用ReceiverRecord作為value,因?yàn)椴粌H包含了receiver對(duì)象窒舟,同時(shí)包含了IntentFilter.所以最終的數(shù)據(jù)結(jié)構(gòu)是HashMap<String,ArrayList<ReceiverRecord>>.
我們來(lái)看Google是怎么實(shí)現(xiàn)的呢?
先來(lái)看兩個(gè)內(nèi)部類:
//內(nèi)部類ReceiverRecord Receiver記錄:用于記錄reciver,對(duì)應(yīng)的IntentFilter和是否在broadcast狀態(tài)
private static class ReceiverRecord {
final IntentFilter filter;
final BroadcastReceiver receiver;
boolean broadcasting;
ReceiverRecord(IntentFilter _filter, BroadcastReceiver _receiver) {
filter = _filter;
receiver = _receiver;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(128);
builder.append("Receiver{");
builder.append(receiver);
builder.append(" filter=");
builder.append(filter);
builder.append("}");
return builder.toString();
}
}
//BroadcastRecord 廣播記錄:用于記錄廣播的intent以及有哪些對(duì)應(yīng)的ReceiverRecord
private static class BroadcastRecord {
final Intent intent;
final ArrayList<ReceiverRecord> receivers;
BroadcastRecord(Intent _intent, ArrayList<ReceiverRecord> _receivers) {
intent = _intent;
receivers = _receivers;
}
}
再來(lái)看幾個(gè)成員變量:
//維護(hù)一個(gè)mReceivers Map 記錄一個(gè)所有的receiver诵盼,每一個(gè)對(duì)應(yīng)哪些Intentfilters惠豺。主要用于記錄當(dāng)前有哪些receiver需要維護(hù)接受廣播。
//方便廣播的反注冊(cè)风宁,反注冊(cè)時(shí)可以快速找到filter從而找到Action,從而操作mAction.試想如果沒(méi)有mReceivers,只能全部遍歷mAction找出所有BroadcastRecord,從而找到filter和Action,性能很差洁墙。
private final HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers
= new HashMap<BroadcastReceiver, ArrayList<IntentFilter>>();
//維護(hù)一個(gè)mActions Map 記錄所有的Action,每一個(gè)對(duì)應(yīng)哪些ReceiverRecord
private final HashMap<String, ArrayList<ReceiverRecord>> mActions
= new HashMap<String, ArrayList<ReceiverRecord>>();
//維護(hù)一個(gè)List,記錄當(dāng)前正處在等待狀態(tài)的廣播BroadcastRecord戒财,通過(guò)BroadcastRecord可以找到intent對(duì)應(yīng)的receivers
private final ArrayList<BroadcastRecord> mPendingBroadcasts
= new ArrayList<BroadcastRecord>();
廣播的發(fā)送過(guò)程
/**
* Register a receive for any local broadcasts that match the given IntentFilter.
*
* @param receiver The BroadcastReceiver to handle the broadcast.
* @param filter Selects the Intent broadcasts to be received.
*
* @see #unregisterReceiver
*/
public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
synchronized (mReceivers) {
ReceiverRecord entry = new ReceiverRecord(filter, receiver);
//查找receiver有沒(méi)有在mReceiver記錄中热监,如果不在需要添加進(jìn)去。
ArrayList<IntentFilter> filters = mReceivers.get(receiver);
if (filters == null) {
filters = new ArrayList<IntentFilter>(1);
mReceivers.put(receiver, filters);
}
//將IntentFilter加入receiver對(duì)應(yīng)的匹配規(guī)則中饮寞。filters為mReceivers map的value,類型是IntentFilter的ArrayList狼纬。
//同一個(gè)receiver可能有多個(gè)IntentFilter。mReceivers就記錄了所有的receiver,并且指明每一個(gè)receiver所能匹配到的IntentFilter.
filters.add(filter);
//開(kāi)始遍歷IntentFilter中的Action.檢查Action是否在mActions,如果不在不要添加進(jìn)去骂际。
//mActions是Action為Key , ArrayList<ReceiverRecord>為value的MAP疗琉。
//記錄了當(dāng)前有那些Action,并且每個(gè)Action對(duì)應(yīng)的Receiver(ReceiverRecord)是哪個(gè)。
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);
}
//將ReceiverRcoder對(duì)象加入entries:entries是該Action對(duì)應(yīng)的ReceiverRecord列表歉铝。
entries.add(entry);
}
}
}
廣播的反注冊(cè)過(guò)程
/**
* Unregister a previously registered BroadcastReceiver. <em>All</em>
* filters that have been registered for this BroadcastReceiver will be
* removed.
*
* @param receiver The BroadcastReceiver to unregister.
*
* @see #registerReceiver
*/
public void unregisterReceiver(BroadcastReceiver receiver) {
synchronized (mReceivers) {
//在Receiver列表中移除要注銷的receiver,返回對(duì)應(yīng)的filters.
ArrayList<IntentFilter> filters = mReceivers.remove(receiver);
if (filters == null) {
return;
}
//在Action Map中移除對(duì)應(yīng)的receiver
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);
//根據(jù)Action獲取receiver列表,移除要?jiǎng)h除的receiver.
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--;
}
}
//如果發(fā)現(xiàn)Action對(duì)應(yīng)的receiver都沒(méi)有刪除掉了盈简,這時(shí)候就需要在Action列表中清空。
//因?yàn)闆](méi)有receiver來(lái)處理這個(gè)Action了太示。
if (receivers.size() <= 0) {
mActions.remove(action);
}
}
}
}
}
}
廣播的發(fā)送過(guò)程:
/**
* Broadcast the given intent to all interested BroadcastReceivers. This
* call is asynchronous; it returns immediately, and you will continue
* executing while the receivers are run.
*
* @param intent The Intent to broadcast; all receivers matching this
* Intent will receive the broadcast.
*
* @see #registerReceiver
*/
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);
//根據(jù)Action從mActions MAP 中取對(duì)應(yīng)的receivers.
ArrayList<ReceiverRecord> entries = mActions.get(intent.getAction());
if (entries != null) {
if (debug) Log.v(TAG, "Action list: " + entries);
ArrayList<ReceiverRecord> receivers = null;
//遍歷receivers找出符合IntentFilter條件的
for (int i=0; i<entries.size(); i++) {
ReceiverRecord receiver = entries.get(i);
if (debug) Log.v(TAG, "Matching against filter " + receiver.filter);
//如果receiver已經(jīng)在分發(fā)中柠贤,不做處理。
if (receiver.broadcasting) {
if (debug) {
Log.v(TAG, " Filter's target already added");
}
continue;
}
//檢查receiver是否和發(fā)送廣播時(shí)傳入的Intent匹配类缤,并加入符合條件的列表receivers
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 是否在分發(fā)中置位true
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);
}
}
}
//將broadcasting置位false 加入mPendingBroadcasts等待隊(duì)列中.
if (receivers != null) {
for (int i=0; i<receivers.size(); i++) {
receivers.get(i).broadcasting = false;
}
mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
//發(fā)送消息MSG_EXEC_PENDING_BROADCASTS
if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
//通過(guò)Handler發(fā)送消息來(lái)處理 mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
}
return true;
}
}
}
return false;
}
可以看到最終把要發(fā)送的廣播加入隊(duì)列mPendingBroadcasts臼勉,然后使用Handler發(fā)送消息給主線程處理的,調(diào)用executePendingBroadcasts()進(jìn)行分發(fā)餐弱。
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);
}
}
}
}
}
LocalBroadcast也支持使用同步的方式進(jìn)行分發(fā):
/**
* Like {@link #sendBroadcast(Intent)}, but if there are any receivers for
* the Intent this function will block and immediately dispatch them before
* returning.
*/
public void sendBroadcastSync(Intent intent) {
if (sendBroadcast(intent)) {
executePendingBroadcasts();
}
}
總結(jié)
1.LocalBroadcast是APP內(nèi)部維護(hù)的一套廣播機(jī)制宴霸,有很高的安全性和高效性。
所以如果有APP內(nèi)部發(fā)送膏蚓、接收廣播的需要應(yīng)該使用LocalBroadcast瓢谢。
2.Receiver只允許動(dòng)態(tài)注冊(cè),不允許在Manifest中注冊(cè)驮瞧。
3.LocalBroadcastManager所發(fā)送的廣播action氓扛,只能與注冊(cè)到LocalBroadcastManager中BroadcastReceiver產(chǎn)生互動(dòng)。