以编程方式注册广播接收器 [英] Programmatically register a broadcast receiver
问题描述
我想知道以编程方式注册广播接收器的最佳实践/方式是什么.我想根据用户选择注册特定的接收者.
I'd like to know what is the best practice/way of programmatically register a broadcast receiver. I want to register specific receivers according to user choice.
由于注册是通过清单文件完成的,我想知道是否有适当的方法可以在代码中实现这一点.
As the registration is done through the manifest file, I'm wondering if there's a proper way to achieve this in code.
推荐答案
听起来您想控制在清单中发布的组件是否处于活动状态,而不是在运行时动态注册接收器(通过 Context.registerReceiver()).
It sounds like you want to control whether components published in your manifest are active, not dynamically register a receiver (via Context.registerReceiver()) while running.
如果是这样,您可以使用 PackageManager.setComponentEnabledSetting() 来控制这些组件是否处于活动状态:
If so, you can use PackageManager.setComponentEnabledSetting() to control whether these components are active:
注意如果你只对在运行时接收广播感兴趣,最好使用 registerReceiver().当您需要确保每次发送广播时都启动您的应用时,接收器组件主要有用.
Note if you are only interested in receiving a broadcast while you are running, it is better to use registerReceiver(). A receiver component is primarily useful for when you need to make sure your app is launched every time the broadcast is sent.
这篇关于以编程方式注册广播接收器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!