简体   繁体   中英

using singleton in kotlin and starting a service

I was trying to make my Service (foreground service) class a singleton like so:

object MyClass: Service() {
}   

when I do this, I can't send an intent to start the service like this:

  val mIntent = Intent(this, MyClass::class.java)
  mIntent.action = MyClass.ACTION_START_FOREGROUND_SERVICE;
  ContextCompat.startForegroundService(this, mIntent)

I get an IllegalAccessException, like this:

Caused by: java.lang.IllegalAccessException: void com.it.gy.MyClass.<init>() is not accessible from java.lang.Class<android.app.AppComponentFactory>  

this exception is supposed to be caused when class at hand is not public, but, object MyClass is supposed to be so by default. I could make the class a public and make a private constructor to implement a custom singleton, but, I'd like to use the Kotlin syntax as far as possible. How may I do that?

What you want is not supported by the operating system. A Service needs to be a class , as Android will want to create an instance of that class.

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