Android-DFU-Library icon indicating copy to clipboard operation
Android-DFU-Library copied to clipboard

Fatal Exception: java.lang.IllegalStateException - Not allowed to start service Intent (app is in background)

Open ReneFerrari opened this issue 3 years ago • 2 comments

DFU Bootloader version (please complete the following information):

  • SDK version: 31
  • Library version: 1.12.0

Device information (please complete the following information):

  • Device: Any device running Android 8 or higher

Describe the bug From time to time we are facing this crash (Android 8 and up due to changes with services). Basically the App is in background and tries to start a service.

The affected LOC is: no.nordicsemi.android.dfu.DfuBaseService.onHandleIntent (DfuBaseService.java:1413)

(Note: It crashes on all startService calls, so not only the one I picked here)

I think changing it to:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    startForegroundService(intent);
} else {
    startService(intent);
}

would probably solve it.

Is there anything speaking against it?

I just checked for Android 12 and up there are unfortunately more restrictions: https://developer.android.com/about/versions/12/behavior-changes-12#foreground-service-launch-restrictions So startForegroundService won't work there, rather WorkManager should be used

ReneFerrari avatar Jan 25 '22 09:01 ReneFerrari

To add a note - we need to add permission FOREGROUND_SERVICE on the consumer to start the foreground service. Here are the additional reference https://developer.android.com/guide/components/foreground-services#request-foreground-service-permissions. It would be nice if we have permission added in the library 👀

Ran this on v2.3.0 at android 13.

junebeans avatar Feb 06 '23 17:02 junebeans

So startForegroundService won't work there, rather WorkManager should be used

Indeed, WorkManager should be used. The library was created long before the first WorkManager existed in a way that it would have to be rewritten separating transport and runner.

You may also disable starting service as foreground at all by setting this to false: https://github.com/NordicSemiconductor/Android-DFU-Library/blob/9123f8b68e65fb45e42146219724ab0c88c17ba3/lib/dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceInitiator.java#L152

philips77 avatar Mar 23 '23 08:03 philips77