Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructor for IntentService (kotlin)

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!

like image 870
Andriy Antonov Avatar asked Nov 24 '16 08:11

Andriy Antonov


People also ask

Does Kotlin have default constructor?

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.

What can I use instead of IntentService?

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.

Why is IntentService deprecated Android?

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.

Can Kotlin object have constructor?

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.


1 Answers

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.

like image 158
miensol Avatar answered Oct 24 '22 06:10

miensol