广播接收器的 Manifest 和 Programmatic 注册的主要区别 [英] Main difference between Manifest and Programmatic registering of BroadcastReceiver
问题描述
我试图了解在清单中注册 BroadcastReceiver 和以编程方式注册它之间的主要区别...
我的理解基本上如下(如果我遗漏了什么,希望有人纠正我的观点).
在清单中注册:
- 如果需要,操作系统会神奇地找到并实例化您的类,调用 onReceive() 方法,无论您的应用程序的运行状态是什么
- 您的接收每次广播只会被调用一次(即您可以认为在清单中注册就像注册您的类"以接收广播 - 广播会根据需要实例化您的类)(??)
以编程方式注册:
- 在代码中注册意味着您正在注册您的类的实例以接收广播消息(即,如果您的代码有点草率,并且您设法注册了多次,您最终会得到多个 BroadcastReceiver 实例,它们都具有它们的 onReceive() 要求广播
- 要取消注册,您需要取消注册您之前注册的特定 BroadcastReceiver 实例
- 如果您的应用程序被操作系统破坏,您的 onReceive() 方法将不会被调用以进行广播
谢谢
基本正确.
请注意,清单注册的接收器对象仅使用一次.为每个广播创建一个 BroadcastReceiver
的新实例.清单注册接收器的主要用途是用于在您的代码不在内存中时可能继续进行的广播(例如,BOOT_COMPLETED
,您通过 AlarmManager
安排的警报).>
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:
- The OS will magically find and instantiate your class if needed, calling the onReceive() method, regardless what the running state of your application was
- 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:
- 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
- to unregister, you need to unregister the specific BroadcastReceiver instance that you previously registered
- if your application gets destroyed by the OS, your onReceive() method will not be called for a broadcast
thanks
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
).
这篇关于广播接收器的 Manifest 和 Programmatic 注册的主要区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!