本文介绍了Android的 - 去在清单中定义一个BroadcastReceiver参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法怎么去从code中的Manifest.xml定义一个BroadcastReceiver的参考?

Is there any way how to get a reference for a BroadcastReceiver defined in Manifest.xml from code?

在我的情况下,我们使用的是需要包含在manifest.xml一个BroadcastReceiver。然而,它具有的功能,我想从我们的code范围内重复使用。因此,而不是创造另一个类似的广播接收器,并从code实例化,我想获得现有的一个参考。

In my case, we are using a BroadcastReceiver that needs to be included in the Manifest.xml. However it has functionality I would like to reuse from within our code. So instead of creating another similar BroadcastReceiver and instantiating it from the code I would like to obtain a reference to the existing one.

其他信息:

我的目标是订阅事件对我的广播接收器从我的活动 - 我想一个事件重复使用 - 而不是我的活动创造这个接收器的另一个实例,我想获得现有的一个参考。

My goal is to subscribe to an event on my BroadcastReceiver from my activity - an event that I would like to reuse - instead of creating another instance of this receiver in my activity I would like to obtain a reference to the existing one.

推荐答案

在注册一个广播接收器在清单,你注册类,而不是它的实例。每一个广播发生时,你的<接收> 需要处理,一个新的实例被创建这样做,所以你不能真正得到你一个参考重新描述。

When registering a BroadcastReceiver in the manifest, you're registering the class, not an instance of it. Each time a broadcast occurs that your <receiver> needs handle, a new instance is created to do so, so you can't really get a reference to one as you're describing.

这是完全正常的动态实例化和注册,你也已经在静态清单注册的接收器类的实例。我想指出,虽然,如果静态注册类将是无论如何运行 - 也就是说,如果它要处理相同的广播的动态登记注册的 - 你可能会考虑只通知你的活动从接收器类 - 例如,用 LocalBroadcastManager ,另一个事件总线实现,等等 - 而不是实质上重复接收器

It's perfectly fine to dynamically instantiate and register an instance of a Receiver class that you've also statically registered in the manifest. I would note, though, that if the statically registered class is going to be run anyway - that is, if it's going to handle the same broadcasts as the dynamically registered one - you might consider just notifying your Activity from the Receiver class - e.g., with LocalBroadcastManager, another event bus implementation, etc. - instead of essentially duplicating Receivers.

这篇关于Android的 - 去在清单中定义一个BroadcastReceiver参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 21:36