简体   繁体   中英

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)

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.

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.

I think you can have a singleton for this and also have a non-default constructor.

You will have to register the broadcast receiver in the code instead of the manifest. In the Activity :

private var broadcastReceiver : MySmsBroadcastReceiver? = null
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val intentFilter = IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)
    broadcastReceiver = MySmsBroadcastReceiver(myArg1, myArg2)
    registerReceiver( broadcastReceiver, intentFilter)
}

But you must also unregister the broadcast receiver manually :

override fun onStop() {
    unregisterReceiver(broadcastReceiver)
    super.onStop()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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