Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android Broadcast 總結

android Broadcast 總結

編輯:關於Android編程

 

 

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 會認為該程序無響應。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved