Search code examples
androidandroid-fragmentsbroadcastreceiver

Registering and unregistering BroadcastReceiver in a fragment


My app has an action bar with 3 fragment tabs. In the second fragment I register and unregister a BroadcastReceiver. I unregister the receiver in onPause and register it in onCreateView and in onResume.

getActivity().registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

and

getActivity().unregisterReceiver(batteryInfoReceiver);

1) Is it all right to register the same reciever twice (in onCreateView and onResume)?(is it harmless?)

2) Is it enough to just register the reciever in onResume?


Solution

  • Have a look at life-cycle of Fragments:

    onCreateView(): The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.

    onResume(): The fragment is visible in the running activity

    onPause(): This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

    Conclusion:

    So it is better to register the receiver only inside onResume() and unregister inside onPause() because onCreateView() deals with view hierarchy only. It has nothing to do with receiver. So it is not harmful but surely it is useless.

    I hope it will be helpful!!