Saturday, 6 July 2013

Using LocalBroadcastManager solve security issue of BroadcastReceiver


BroadcastReceiver in Android is designed is to facilitate comunication betweeon different applications. Therefore, secuirty issue may exists if the communication is intend for a single application only. Normally , you can solve by:

(1) Specify the permission of the receiver in sendBroadcast(Intent, String) method
(2) Use Intent.setPackage to assign the target of the broadcast

Actually, there is another method to get rid of the security issue. Android v4 compatibility package provides android.support.v4.content.LocalBroadcastManager. This helps you to perform broadcast within you own application.

LocalBroadcastManager mLocalBroadcastManager;    
  BroadcastReceiver mReceiver;    
  
  
 IntentFilter filter =  new  IntentFilter();    
 filter.addAction( "test" );    


 mReceiver =  new  BroadcastReceiver() {    
            @Override    
            public  void  onReceive(Context context, Intent intent) {    
                if  (intent.getAction().equals( "test" )) {    
                    //Do Something  
                }   
            }    
        };

mLocalBroadcastManager.registerReceiver(mReceiver, filter);          


unregistered it in the onDestroy method:
 @Override  
protected  void  onDestroy() {  
  
   super .onDestroy();  
  
   mLocalBroadcastManager.unregisterReceiver(mReceiver);  
  
}

0 comments:

Post a Comment