0

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

djlj
  • 31
  • 2
  • 6

1 Answers1

0
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" />
Vlad
  • 7,997
  • 3
  • 56
  • 43
  • Thanks! It looks good but there's an error: `Unresolved reference: enqueueWork`. I found this: https://stackoverflow.com/a/54207056/15309916 - but `SecondClass.enqueueWork` not works too. – djlj Mar 03 '21 at 09:37
  • @djlj yes, it is. Try via `JobIntentService.enqueueWork` – Vlad Mar 03 '21 at 09:54
  • Yes! Gradle Build works right now but application crashes when i tap to "Start" with this error: `Scheduled service ComponentInfo{com...SecondClass} does not require android.permission.BIND_JOB_SERVICE permission`. I use `BIND_JOB_SERVICE` for a long time in the manifest. I tried delete it - without success. – djlj Mar 03 '21 at 11:19
  • @djlj see my answer at the end – Vlad Mar 03 '21 at 12:09
  • I was using `android:permission="ACCESS_BACKGROUND_LOCATION|ACCESS_COARSE_LOCATION|ACCESS_FINE_LOCATION|ACCESS_LOCATION_EXTRA_COMMANDS|ACCESS_MEDIA_LOCATION|CONTROL_LOCATION_UPDATES|INSTALL_LOCATION_PROVIDER|LOCATION_HARDWARE|android.permission.BLUETOOTH"` I changed it to `android:permission="android.permission.BIND_JOB_SERVICE"`. New error: `Unable to instantiate service com...SecondClass: java.lang.InstantiationException: java.lang.Class cannot be instantiated` :'( – djlj Mar 03 '21 at 14:30
  • I guess you added permission to incorrect place, it should be in `manifest/app/service` – Vlad Mar 03 '21 at 16:00
  • I checked it 100×. It's in manifest/app/service. But still this error. Kotlin is amazing but I'm confused from this weird errors. – djlj Mar 03 '21 at 20:18
  • I solved it. I don't know how but it's solved. Thank you especially for `enqueueWork`. – djlj Mar 15 '21 at 11:37