Dinorah Tovar Dinorah Tovar - 1 year ago 119
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");

Inside MainActivity I have the receiver

private BroadcastReceiver loginReceiver = new BroadcastReceiver() {
public void onReceive(Context arg0, Intent arg1) {

onPause and onResume on the MainActivity

protected void onResume() {
new IntentFilter("RELOAD_MENU"));

protected void onPause() {
//LocalBroadcastManager onPause

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download