Dinorah Tovar Dinorah Tovar - 3 months ago 26
Android Question

LocalBroadcastManager, redundant activities, Activity lifecycle

I have a big application, our first activity is MainActivity the second one is a LoginActivity (For multiple reason can be a Fragment or a DialogFragment)

The LoginActivity is initialized by MainActivity, in a normal flow, the application need to reload the header in a NavigationDrawer.
I already have a function like this, in MainActivity.

private void loadUser () {
//Reload header
}


Inside the LoginActivity I have a LocalBroadcastManager like the next one

Intent intent = new Intent ("RELOAD_MENU");
LocalBroadcastManager.getInstance(c).sendBroadcast(intent);


Inside MainActivity I have the receiver

private BroadcastReceiver loginReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
loadUser();
}
};


onPause and onResume on the MainActivity

@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(loginReceiver,
new IntentFilter("RELOAD_MENU"));
}


@Override
protected void onPause() {
//LocalBroadcastManager onPause
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(loginReceiver);
}


I missing something?

There is a problem with Activity A initialize Activity B and then Activity B start a LocalBroadcast that the Activity A must heard?

I also make some test with onDestroy just for testing, Im not receiving the LocalBroadcast.

Answer

The problem is that you're unregistering the receiver in MainActivity's onPause () method.

You probably want to register the receiver in onCreate() and unregister in onDestroy(), otherwise when you call LocalBroadcastManager.getInstance(c).sendBroadcast(intent); in LoginActivity, there are no listeners registered with the LocalBroadcastManager because MainActivity is paused while LoginActivity is visible on the screen.

Comments