Android – Main difference between Manifest and Programmatic registering of BroadcastReceiver

androidandroid-lifecyclebroadcastreceiver

I am trying to understand the main differences between registering a BroadcastReceiver in the Manifest and registering it programmatically…

My understanding is basically as follows (would appreciate someone correcting my points if I am missing something).

  • Registered in Manifest:

    1. The OS will magically find and instantiate your class if needed, calling the onReceive() method, regardless what the running state of your application was
    2. Your receive will only get called once per broadcast (i.e. You can consider that registering in the manifest is like registering your 'class' for receiving the broadcast – and the broadcast instantiates your class as needed) (??)
  • Registered Programmatically:

    1. registering in code means that you are registering instances of your class to receive broadcast messages (i.e. if your code is a little sloppy, and you manage to register several times, you will end up with multiple BroadcastReceiver instances all having their onReceive() called for a broadcast
    2. to unregister, you need to unregister the specific BroadcastReceiver instance that you previously registered
    3. if your application gets destroyed by the OS, your onReceive() method will not be called for a broadcast

thanks

Best Answer

You have it basically correct.

Note that a manifest-registered receiver object is only used once. A new instance of your BroadcastReceiver is created for each broadcast. The primary use of manifest-registered receivers is for broadcasts that may go on while your code is not in memory (e.g., BOOT_COMPLETED, your scheduled alarms via AlarmManager).