I am new with Kotlin and little bit stack with intentService. Manifest shows me an error that my service doesn't contain default constructor, but inside service it looks ok and there are no errors.
Here is my intentService:
class MyService : IntentService {
constructor(name:String?) : super(name) {
}
override fun onCreate() {
super.onCreate()
}
override fun onHandleIntent(intent: Intent?) {
}
}
I was also try another variant:
class MyService(name: String?) : IntentService(name) {
but when I try to run this service I still get an error:
java.lang.Class<com.test.test.MyService> has no zero argument constructor
Any ideas how to fix default constructor in Kotlin?
Thanks!
Every Kotlin class needs to have a constructor and if we do not define it, then the compiler generates a default constructor. A Kotlin class can have following two type of constructors: Primary Constructor. Second Constructors.
Consider using WorkManager or JobIntentService , which uses jobs instead of services when running on Android 8.0 or higher. IntentService is an extension of the Service component class that handles asynchronous requests (expressed as Intent s) on demand. Clients send requests through Context.
Provided since Android API 3, the purpose of IntentService was to allow asynchronous tasks to be performed without blocking the main thread. The deprecation is one of a number of steps introduced starting with Android 8.0 (API 26) to limit the actions that can be performed while an app is in the background.
ConstructorsA class in Kotlin can have a primary constructor and one or more secondary constructors. The primary constructor is a part of the class header, and it goes after the class name and optional type parameters.
As explained here your service class needs to have parameterless consturctor. Change your implementation to in example:
class MyService : IntentService("MyService") {
override fun onCreate() {
super.onCreate()
}
override fun onHandleIntent(intent: Intent?) {
}
}
The Android documentation on IntentService states that this name is only used for debugging:
name
String
: Used to name the worker thread, important only for debugging.
While not stated explicitly, on the mentioned documentation page, the framework needs to be able to instantiate your service class and expects there will be a parameterless constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With