Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register to local broadcast inside a custom view

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?

like image 213
Dror Fichman Avatar asked Mar 24 '13 11:03

Dror Fichman


People also ask

How do I send a local broadcast?

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.

When should I use LocalBroadcastManager?

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.


1 Answers

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();
}
like image 137
vggonz Avatar answered Oct 05 '22 22:10

vggonz