I've created a custom view which can be placed on different places in the application. I can't avoid using a BroadcastReceiver inside the view to get messages from the rest of the application.
I've read it's not recommended (Where should I unregisterReceiver in my own view?), but in case I choose to use it is there a place to unregister the view from the BroadcastManager?
sendBroadcast(localIntent); Now create a broadcast receiver that can respond to the local-broadcast action: private BroadcastReceiver listener = new BroadcastReceiver() {@Override public void onReceive( Context context, Intent intent ) { String data = intent. getStringExtra(“DATA”); Log.
If you want some kind of broadcasting in your application then you should use the concept of LocalBroadcastManager and we should avoid using the Global Broadcast because for using Global Broadcast you have to ensure that there are no security holes that can leak your data to other applications.
I suggest you to use a LocalBroadcastManager. It's like a BroadcastReceiver whose Intents can only be seen inside your application.
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// your code here
}
};
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onPause();
}
@Override
protected void onResume() {
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
IntentFilter filter = new IntentFilter();
filter.addAction(MyClass.MY_ACTION);
lbm.registerReceiver(receiver, filter);
super.onResume();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With