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.     }  




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章