@@@描述 廣播接收器可以收到 Context.sendBroadcast或者Context.sendOrderedBroadcast發出的意圖(intent)。 @@@LocalBroadcastManager 如果你不需要誇應用發送廣播,建議你使用 LocalBroadcastManager,
@@@描述 廣播接收器可以收到
Context.sendBroadcast
或者Context.sendOrderedBroadcast發出的意圖(intent)。
@@@LocalBroadcastManager
如果你不需要誇應用發送廣播,建議你使用 LocalBroadcastManager, LocalBroadcastManager 是一個幫助類,幫助你方便的在
當前應用
中註冊廣播接收 器和發送廣播。並且和發送全局廣播比起來,他還有如下優勢:
1,不用擔心私有數據的安全性,因為發送的廣播不會讓除當前應用之外的其他應用接收到。
2,不用擔心其他應用會利用你的安全漏洞,因為其他應用不可能通過 LocalBroadcastManager向你發送廣播。
3,它比發送全局廣播更加高效。
LocalBroadcastManager的常用方法如下:


AndroidManifest.xml
中添加<receiver>
標簽靜態註冊。
動態註冊方式:如果你在 Activity.onResume()註冊一個廣播接收器,你應該在
Activity.onPause()註銷這個它
. (當Activity Pause的時候,你不會接受到廣播,如果你不在 Activity.onPause()中註銷,將會帶來極大的資源消耗。
). 不要在Activity.onSaveInstanceState()中註銷一個廣播接收器
, 因為該方法不會在用戶移動到歷史堆棧中其他Activity的時候被調用。
靜態註冊方式:













onReceive(Context, Intent)方法被調用的時候才有效,一旦 onReceive(Context, Intent)方法的代碼唄返回,廣播接收器的對象將不再有效。這個主要的影響就是你能在 onReceive(Context, Intent)方法中執行什麼操作,任何有關非同步的操作是無用的,因為當非同步操作執行完成後, onReceive(Context, Intent)方法已經執行完,廣播接收器對象已不再有效或者被系統回收。
2,通常情況下,你不能在 onReceive(Context, Intent)方法中彈出一個對話框,或者綁定一個service,對於前者,你可以用NotificationManager
來代替,對於後者,你可以調用Context.startService()
方法來代替。對於耗時操作應該在Service中執行。