android Broadcast 總結

來源:互聯網
上載者:User

標籤:cti   family   cal   好的   end   uri   err   round   font   



   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 總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.