Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 407
Thomas Oo Avatar asked Nov 07 '16 18:11

Thomas Oo


2 Answers

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.

like image 139
CommonsWare Avatar answered Sep 19 '22 00:09

CommonsWare


BroadcastReceiver is an abstract class, which a class must extend in order to be registered as a receiver on your Manifest. You cannot change the scope of its methods once you extend it and you cannot enforce a Singleton pattern on it. If you are trying to set a Singleton as your BroadcastReceiver, there may be an issue with your design.

like image 33
Bret Deasy Avatar answered Sep 20 '22 00:09

Bret Deasy