Search code examples
androidandroid-studiobackgroundbroadcastreceiver

Why Unregister Broadcast Receiver when I want to receive broadcast even when app is closed?


this might sound silly but. If I unregister a receiver once my app is closed, I won't be able to receive intents to that BroadcastReceiver right?? If so wouldn't that defeat the purpose?


Solution

  • If I unregister a receiver once my app is closed, I won't be able to receive intents to that BroadcastReceiver right?

    Yes, if you unregister a receiver via unregisteReceiver() that you registered via registerReceiver(), that receiver will no longer receive broadcasts.

    If so wouldn't that defeat the purpose?

    Not really.

    You seem to be worried about when your app is "closed". The verb "closed" is not very specific in this context, but once your app's UI moves to the background, your process can be terminated at any point in time. When your process is terminated, any receivers that you register with registerReceiver() vanish, along with everything else in the process. Registering a receiver dynamically is only useful while your process is running. So, whether you call unregisterReceiver() or not, when your app is "closed", you will soon be unable to receive broadcasts.

    The primary alternative to registerReceiver() is to register a <receiver> in the manifest. On modern versions of Android, though, manifest-registered receivers cannot receive many broadcasts.