標籤:
1, 生命週期
在android官方文檔中,推薦我們在onResume中進行 registerReceiver, 在onPause中進行unRegisterReceiver, 他們給出的理由是:
If registering a receiver in your Activity.onResume() implementation, you should unregister it in Activity.onPause(). (You won‘t receive intents when paused, and this will cut down on unnecessary system overhead). Do not unregister in Activity.onSaveInstanceState(), because this won‘t be called if the user moves back in the history stack.
2,有序廣播和無序廣播的區別
廣播接收者(BroadcastReceiver)用於監聽系統事件或應用程式事件,通過調用Context.sendBroadcast()、Context.sendOrderedBroadcast()可以向系統發送廣播意圖,通過廣播一個意圖(Intent)可以被多個廣播接收者所接收,從而可以在不用修改原始的應用程式的情況下,讓你對事件作出反應。
其中Context.sendBroad()主要是用來廣播無序事件(也被稱為有序廣播 Normal broadcast),即所有的接收者在理論上是同時接收到事件,同時執行的,對訊息傳遞的效率而言這是比較好的做法。而Context.sendOrderedBroadcast()方法用來向系統廣播有序事件(Ordered broadcast),接收者按照在Manifest.xml檔案中設定的接收順序依次接收Intent,順序執行的,接收的優先順序可以在系統設定檔中設定(聲明在intent-filter元素的android:priority屬性中,數值越大優先順序別越高,其取值範圍為-1000到1000。當然也可以在調用IntentFilter對象的setPriority()方法進行設定)。對於有序廣播而言,前面的接收者可以對接收到得廣播意圖(Intent)進行處理,並將處理結果放置到廣播意圖中,然後傳遞給下一個接收者,當然前面的接收者有權終止廣播的進一步傳播。如果廣播被前面的接收者終止後,後面的接收器就再也無法接收到廣播了。
3, 持久廣播 sendStickyBroadcast
sticky 類型的廣播會儲存 上次廣播的intent, 只要你註冊到這個廣播, 就可以直接獲得上次的intent 。(直到removeStickyBroadcast 該廣播)
Perform a sendBroadcast(Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).
You must hold the BROADCAST_STICKY permission in order to use this API. If you do not hold that permission,SecurityException will be thrown.
大概的意思是說: 發出的廣播會一直滯留(等待),以便有人註冊這則廣播訊息後能儘快的收到這條廣播。其他功能與sendBroadcast相同。但是使用sendStickyBroadcast 發送廣播需要獲得BROADCAST_STICKY permission,如果沒有這個permission則會拋出異常。
而有序類型的廣播,則不會儲存intent, 如果當時沒得到intent,則以後也得不到。
4, 廣播生命週期
每次廣播到來時 , 會重新建立 BroadcastReceiver 對象 , 並且調用 onReceive() 方法 , 執行完以後 , 該對象即被銷毀 . 當 onReceive() 方法在 10 秒內沒有執行完畢, Android 會認為該程式無響應。
android Broadcast 總結