Thomas Oo Thomas Oo - 1 year ago 132
Android Question

BroadcastReceiver has no default constructor in android manifest

I am trying to register a class that extends BroadcastReceiver as a receiver in Android manifest. I have no trouble registering them but the problem occurs because of the class does not have an empty constructor.

  1. I don't understand why BroadcastReceiver requires an empty constructor, is there a way around this?

  2. I could make a public empty constructor in my class but the problem is, this class is also a singleton class. Which means I do not want this class to use the empty constructor! There is an obvious conflict here, I could just write an empty constructor and trust users do not ever use it by writing documentation but there has to be a simpler method right?

TLDR; How to implement a class that is a broadcast receiver (requires empty constructor to register it in android manifest) but at the same time, be a singleton class or a class that denies users access to the default constructor. (I've tried making the default constructor protected but that does not solve the problem as the manifest cannot register the receiver)

Answer Source

is there a way around this?

No. Android has no idea how to invoke any other constructor, or what values to pass to that constructor.

this class is also a singleton class

That is not possible. Android will create a new instance of your manifest-registered BroadcastReceiver for every broadcast that it receives.

but there has to be a simpler method right?

Yes: do not make the BroadcastReceiver a singleton. Make some other class be the singleton, that the BroadcastReceiver uses.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download