Dror Fichman Dror Fichman - 1 month ago 22
Android Question

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?

Answer

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();
}