1 .應用內廣播消息:在應用中發送廣播通信的話優先使用LocalBroadcastManager 來完成,因為LocalBroadcastManager是通過handler的方式來實現的,比起我們平時使用的BroadcastReceiver方式開銷要小很多(BroadcastReceiver是通過binder的形式,比如我們接收的MEIDA_MOUNTED的廣播消息就是跨進程的形式),看下源碼下面的解釋應該就很清楚了,在應用內使用LocalBroadcastManager更加的安全,
/**
* Helper to register for and send broadcasts of Intents to local objects
* within your process. This is has a number of advantages over sending
* global broadcasts with {@link android.content.Context#sendBroadcast}:
* <ul>
* <li> You know that the data you are broadcasting won't leave your app, so
* don't need to worry about leaking private data.
* <li> It is not possible for other applications to send these broadcasts to
* your app, so you don't need to worry about having security holes they can
* exploit.
* <li> It is more efficient than sending a global broadcast through the
* system.
* </ul>
*/
public class LocalBroadcastManager {
}
LocalBroadcastManager 只能通過代碼動態注冊不能通過xml形式,下面寫一下他的使用方法:
//廣播類型
public static final String ACTION_SEND = "1";
//自定義廣播接收者
public class AppBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//TODO
}
}
//創建廣播接收者
AppBroadcastReceiver appReceiver = new AppBroadcastReceiver();
//注冊
LocalBroadcastManager.getInstance(context).registerReceiver(appReceiver, new IntentFilter(ACTION_SEND));
//發送
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(ACTION_SEND));
//注銷
LocalBroadcastManager.getInstance(context).unregisterReceiver(appReceiver);
這里也順便講一下 關于廣播的知識,廣播類型分為3種:
- normal:普通廣播(Normal broadcasts),普通廣播是完全異步的,可以被所有的接收者收到,但是時間可能根據環境有先后,但是可以發送給所有的接收者。發送方式為:Context.sendBroadcast()
- order:有序廣播是按照接收者的優先級別發送給接受者的,優先級高的先收到,優先級別高的接收到廣播后有權取消掉這個廣播,不讓下一個接收者接收,或者給當前接收的消息添加一些你處理過后的信息再傳給下一個接受者.發送方式為:Context.sendOrderedBroadcast()
- sticky 類型:看過android broadcast文檔的應該清楚,發送方式為:*Context.sendStickyBroadcast(intent); *,sticky形式的廣播需要添加 BROADCAST_STICKY permission,這個廣播的意思就是 發送這個廣播后會保留最后一條廣播的消息,等到有新的注冊者后把最后一條(最新的)消息發送給他,比如我們在應用里面注冊的MEIDA_MOUNTED廣播消息,在沒有進入你的應用時你進行插拔卡的動作,完成之后等到你進入到你的應用這個時候你才注冊你的廣播你仍然是可以收到廣播消息的。它將發出的廣播保存起來,一旦發現有人注冊這條廣播,則立即能接收到。