Search code examples
androidbroadcastreceiveronpauseondestroy

Where should I unregister a BroadcastReceiver if I intend on receiving broadcasts even when the app is in the background?


For my purpose, I need to listen to CONNECTIVITY_CHANGE broadcasts as long as the app is running (foreground or background).

If I unregister in the onDestroy() method, I lose the receiver if I navigate back to the first activity, since the first activity is brought to the top.

If I unregister in onPause(), I can't listen to changes when the app is running in the background but not killed.

This is causing the receiver to leak intent when the app is killed forcefully.

What would an ideal solution for my case be?

Thanks in advance :)


Solution

  • If the app is force stopped, it will leak no matter what you do. When you're force stopped you don't get a chance to unregister anything.

    But in the larger spirit of your question- if you need a place to register a long term receiver and later unregister it, the answer is in a Service.