简体   繁体   English

如果要在清单中注册,是否可以将 BroadcastReceiver 实现为单例?

[英]Is it possible to implement a BroadcastReceiver as a singleton if it's to be registered in the manifest?

I'm creating a BroadcastReceiver which is to be registered under as an application component in the manifest.我正在创建一个 BroadcastReceiver,它将作为清单中的应用程序组件注册。

I'd like to ensure that there is only one instance of this class.我想确保这个类只有一个实例。 Is it possible to enforce a singleton pattern for this class?是否可以为此类强制执行单例模式? Making the constructor private in this case doesn't work because the system is then unable to instantiate it, and returns a NullPointerException.在这种情况下将构造函数设为私有不起作用,因为系统随后无法实例化它,并返回 NullPointerException。

Is it possible to enforce a singleton pattern for this class?是否可以为此类强制执行单例模式?

No, sorry.不,对不起。 The framework will create one instance per received broadcast, and that is not changeable, given that you are registering for it in the manifest.框架将为每个接收到的广播创建一个实例,并且这是不可更改的,因为您正在清单中注册它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM