LocalBroadCast与BroadCast

来源:互联网 发布:淘宝搜店铺名搜不到 编辑:程序博客网 时间:2024/05/24 02:34
  • 以下是谷歌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.     }  




原创粉丝点击