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广播消息,在没有进入你的应用时你进行插拔卡的动作,完成之后等到你进入到你的应用这个时候你才注册你的广播你仍然是可以收到广播消息的。它将发出的广播保存起来,一旦发现有人注册这条广播,则立即能接收到。