android 应用广播

2016-06-27  本文已影响51人  JeremyDai

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种:

上一篇下一篇

猜你喜欢

热点阅读