Kotlin: How to call JobIntentService from Fragment?

390 views Asked by At

I'm creating GPS tracking app. So I need to run this app at background (or foreground?). How can I call JobIntentService (SecondClass) class when I tap to button "Start" in Fragment (FirstClass)?

I looked for example at this code - but still I don't understand how to call JobIntentService class from Fragment class.

I try to call SecondClass like this (source):

val contentIntent = Intent(context, SecondClass::class.java)

But it ends with this error: java.lang.RuntimeException: Unable to instantiate service com...SecondClass: java.lang.InstantiationException: java.lang.Class<com...SecondClass> cannot be instantiated

1

There are 1 answers

8
Vlad On
context?.run {
    JobIntentService.enqueueWork(
        applicationContext,
        SecondClass::class.java,
        100,// your id
        Intent(applicationContext, SecondClass::class.java)
    )
}

Don't forget to declare service in manifest in such way

<service
    android:name=".SecondClass"
    android:permission="android.permission.BIND_JOB_SERVICE" />