Main difference between Manifest and Programmatic registering of BroadcastReceiver

前端 未结 3 2024
一生所求
一生所求 2020-12-05 14:03

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

My understanding is bas

相关标签:
3条回答
  • 2020-12-05 14:36

    Your understanding is correct according to mine.

    Another relevant (and obscure) difference is that some specific system Intents will only trigger your receiver if it's programmatically registered. Receivers only defined in the manifest won't be called. Examples are: ACTION_SCREEN_ON, ACTION_SCREEN_OFF, ACTION_BATTERY_CHANGED, ACTION_HEADSET_PLUG

    I'd recommend this text that mentions various details about Intents and Receivers.

    0 讨论(0)
  • 2020-12-05 14:40

    When to use which method to register

    Which method to use for registering your BroadcastReceiver depends on what your app does with the system event. I think there are basically two reasons why your app wants to know about system-wide events:

    1. Your app offers some kind of service around these events

    2. Your app wants to react graciously to state changes

    Examples for the first category are apps that need to work as soon as the device is booted or that must start some kind of work whenever an app is installed. Battery Widget Pro or App2SD are good examples for these kinds of apps. For this type you must register the BroadcastReceiver in the Manifest file.

    Examples for the second category are events that signal a change to circumstances your app might rely on. Say your app depends on an established Bluetooth connection. You have to react to a state change – but only when your app is active. In this case there is no need for a statically registered broadcast receiver. A dynamically registered one would be more reasonable.

    There are also a few events that you are not even allowed to statically register for. An example for this is the Intent.ACTION_TIME_TICK event which is broadcast every minute. Which is a wise decision because a static receiver would unnecessarily drain the battery.

    0 讨论(0)
  • 2020-12-05 14:42

    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).

    0 讨论(0)
提交回复
热议问题