LocalBroadCast与BroadCast

  • 以下是谷歌api官方文档
  • The LocalBroadcastManager.sendBroadcast method sends broadcasts to receivers that are in the same app as the sender. If you don't need to send broadcasts across apps, use local broadcasts. The implementation is much more efficient (no interprocess communication needed) and you don't need to worry about any security issues related to other apps being able to receive or send your broadcasts.
  • 由此得知使用LocalBroadCast有如下好处

1    因广播数据在本应用范围内传播,你不用担心隐私数据泄露的问题。

2    不用担心别的应用伪造广播,造成安全隐患。

3    相比在系统内发送全局广播,它更高效。

其使用方法也和正常注册广播类似:

具体demo

这里使用LocalBroadcastManager这个单例类来进行实现,具体操作代码如下:

定义一个action:

[java]  view plain  copy
  1. /** 
  2.  * 自定义广播 
  3.  */  
  4. public static final String LOGIN_ACTION = "com.wits.action.LOGIN_ACTION";  

然后封装发送广播:

[java]  view plain  copy
  1. /** 
  2.      * 发送我们的局部广播 
  3.      */  
  4.     private void sendBroadcast(){  
  5.         LocalBroadcastManager.getInstance(this).sendBroadcast(  
  6.                 new Intent(LOGIN_ACTION)  
  7.         );  
  8.     }  

广播接收者:

[java]  view plain  copy
  1. /** 
  2.      * 自定义广播接受器,用来处理登录广播 
  3.      */  
  4.     private class LoginBroadcastReceiver extends BroadcastReceiver{  
  5.   
  6.         @Override  
  7.         public void onReceive(Context context, Intent intent) {  
  8.             //处理我们具体的逻辑,更新UI  
  9.         }  
  10.     }  
注册与取消

[java]  view plain  copy
  1. //广播接收器  
  2.     private LoginBroadcastReceiver mReceiver = new LoginBroadcastReceiver();  
  3.   
  4.     //注册广播方法  
  5.     private void registerLoginBroadcast(){  
  6.         IntentFilter intentFilter = new IntentFilter(LoginActivity.LOGIN_ACTION);  
  7.         LocalBroadcastManager.getInstance(mContext).registerReceiver(mReceiver,intentFilter);  
  8.     }  
  9.   
  10.     //取消注册  
  11.     private void unRegisterLoginBroadcast(){  
  12.         LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mReceiver);  
  13.     }  




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值