Is it better code practice to register a receiver in manifest or in code?

前端 未结 4 1619
北恋
北恋 2021-01-18 07:19

I\'m writing a simple broadcast receiver. I\'ve registered receivers in both the manifest and in the code before. For my purposes this is a simple receiver that doesn\'t nee

4条回答
  •  误落风尘
    2021-01-18 08:02

    I can't speak as to the efficiency of the implementation of one over the other (my intuition tells me that it's too close to really matter), but for reasons hinted at in Cristian's answer, registering and unregistering programmatically might make your app more efficient.

    If you register in the manifest, your broadcast receiver will always be woken up by any intents that match your filters. If you register programmatically, you can only allow your receiver to be woken up at particular times, and you can control which intents will wake up your receiver and at which times.

    If you're really worried about waking up the receiver at times that it doesn't need to be, then do it programmatically in the code. You'll need to be more careful to always unregister, and ensure that your receiver is registered at all times that you expect it to be, but if you do that correctly, you can avoid waking up your receiver unnecessarily, and thus saving some efficiency.

提交回复
热议问题