使用LocalBroadcastManager app内部广播发送和接收

来源:互联网 发布:linux配置ssh服务 编辑:程序博客网 时间:2024/05/16 17:25

LocalBroadcastManager是Android Support包提供了一个工具,是用来在同一个应用内的不同组件间发送Broadcast的。

使用LocalBroadcastManager有如下好处:

  • 发送的广播只会在自己App内传播,不会泄露给其他App,确保隐私数据不会泄露
  • 其他App也无法向你的App发送该广播,不用担心其他App会来搞破坏
  • 比系统全局广播更加高效

和系统广播使用方式类似:

先通过LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this); 获取实例

然后通过函数 registerReceiver来注册监听器

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. lbm.registerReceiver(new BroadcastReceiver() {  
  2.         @Override  
  3.         public void onReceive(Context context, Intent intent) {  
  4.         // TODO Handle the received local broadcast  
  5.         }  
  6.     }, new IntentFilter(LOCAL_ACTION));  
  7.   
  8. Read more: http://blog.chengyunfeng.com/?p=498#ixzz2l9b1fFR2  

通过 sendBroadcast 函数来发送广播
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. lbm.sendBroadcast(new Intent(LOCAL_ACTION));  


0 0
原创粉丝点击