BroadcastReceiver(廣播接收器),屬于 Android 四大組件之一,在分析ANR產生原因時,涉及到部分廣播的知識,我將針對廣播型別,做個記錄:
1. 普通廣播(Normal Broadcast)
即開發者自身定義intent的廣播(最常用),也就是并行廣播,發送廣播使用如下:
Intent intent = new Intent();
//對應BroadcastReceiver中intentFilter的action
intent.setAction(BROADCAST_ACTION);
//發送廣播
sendBroadcast(intent);
2. 有序廣播(Ordered Broadcast)
定義(也就是串行廣播)::
發送出去的廣播被廣播接收者按照先后順序接收
有序是針對廣播接收者而言的
廣播接受者接收廣播的順序規則(同時面向靜態和動態注冊的廣播接受者)
按照Priority屬性值從大-小排序;
Priority屬性相同者,動態注冊的廣播優先;
特點:
接收廣播按順序接收
先接收的廣播接收者可以對廣播進行截斷,即后接收的廣播接收者不再接收到此廣播;
先接收的廣播接收者可以對廣播進行修改,那么后接收的廣播接收者將接收到被修改后的廣播
具體使用
有序廣播的使用程序與普通廣播非常類似,差異僅在于廣播的發送方式:
sendOrderedBroadcast(intent);
3、前臺廣播和后臺廣播
Android的廣播有前臺廣播和后臺廣播的區別,他們分別對應一個佇列,前臺廣播對應的是前臺佇列,后臺廣播對應的是后臺佇列,
/**
91 * Lists of all active broadcasts that are to be executed immediately
92 * (without waiting for another broadcast to finish). Currently this only
93 * contains broadcasts to registered receivers, to avoid spinning up
94 * a bunch of processes to execute IntentReceiver components. Background-
95 * and foreground-priority broadcasts are queued separately.
96 */
97 final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
98
99 /**
100 * List of all active broadcasts that are to be executed one at a time.
101 * The object at the top of the list is the currently activity broadcasts;
102 * those after it are waiting for the top to finish. As with parallel
103 * broadcasts, separate background- and foreground-priority queues are
104 * maintained.
105 */
106 final ArrayList<BroadcastRecord> mOrderedBroadcasts = new ArrayList<>();
在發送廣播時,可以通過設定Intent.FLAG_RECEIVER_FOREGROUND屬性來將廣播定義為前臺廣播,如果未定義,默認使用后臺廣播,
Intent intent = new Intent("android.intent.action.xxx");
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
sendBroadcast(intent);
前臺廣播和后臺廣播超時時間是不一樣的,前臺廣播是BROADCAST_FG_TIMEOUT(10s),后臺廣播是BROADCAST_BG_TIMEOUT(60s),這里的超時時間是指單個廣播接收器可以處理的最大時間,
通過對原始碼的分析,可以得出一條重要的結論:只有串行佇列中的接收器存在超時問題,如果是普通廣播,以及動態注冊的接收器是不存在超時的,
了解了超時機制,可以總結一下前臺廣播和后臺廣播,
如果我們希望廣播能夠更快地被接收,那么就可以將其定義成前臺廣播,前臺廣播為什么比后臺廣播快呢?主要有以下幾點原因:
1、系統默認的廣播是后臺廣播,因此前臺廣播佇列比后臺廣播佇列空閑,
2、前臺廣播的超時時間是10s,后臺廣播的超時時間是60s,開發者必須限制前臺廣播的數量,否則會導致ANR,同時在接收器不能有耗時的操作,
3、如果BroadcastQueue正在處理一個串行佇列中的BroadRecord,當此時發送普通廣播,對應動態注冊的接收器還是可以收到的,有序廣播或者靜態注冊的接收器需要排隊,這也是并行處理和串行處理的區別,
具體分析,可以參考文章https://blog.csdn.net/wangsen927/article/details/116298801
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/282134.html
標籤:其他
