11

enter image description here

I received this error report through Fabric.io in both Android 8.0 and Android 7.x.

Since it's not just specific classes that fail, I do not know how to handle them.

Please help me if you have any ideas.

SurvivalMachine
  • 7,946
  • 15
  • 57
  • 87
Hoang Duc Tuan
  • 415
  • 1
  • 4
  • 15

1 Answers1

7

In Android O, we have a new background limitations. When you're trying to startService(), you will get IlleagalStateException, so now you should use startForegroundService(), but if you start service by this new method, you will get error like on your screenshot. To avoid this exception you have 5 seconds to make startForeground() after startForegroundService(), to notify user, that you're working in background.

So, where is only one way in Android O:

context.startForegroundService(intent)

And in service onCreate() make something like that:

startForeground(1, new Notification());

UPDATE So as i assume, some manufacturers have backport on Android N these new background limitations, that's why you can get same exception in Android N.

HeyAlex
  • 1,666
  • 1
  • 13
  • 31
  • Thank @Andrew Browiski. But I received it both Android 8.0 and 7.x – Hoang Duc Tuan Sep 28 '17 at 10:47
  • @Hoang Duc Tuan, in Android N_MR1 you can't use startForegroundService actually. Maybe you can post some code? – HeyAlex Sep 28 '17 at 10:51
  • my code: `if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(intent); } else { context.startService(intent); }` – Hoang Duc Tuan Sep 29 '17 at 04:59
  • 3
    I start a service in `onCreate` of the `MainActivity`. And call `startForeground` in both `onCreate` and `onStartCommand` of the `Service`. The app should be always in the foreground state while it's calling `onCreate`. But I'm still receiving this error. – Kimi Chiu Oct 18 '17 at 05:33
  • @Kimi Chiu, is it in Android O? – HeyAlex Oct 18 '17 at 08:09
  • @AndrewBrowiski, Yes it is. – Kimi Chiu Oct 18 '17 at 09:31
  • @Hoang Duc Tuan, so now i can say, why you have this error. Some vendors make backport for these limitions in Android N. What's why you have this exception – HeyAlex Nov 17 '17 at 11:52
  • The others said that it may occurs while the service was killed before the assertion. But we can't control this behavior on the user's device. Sometimes the service will be killed immediately while it's updating from Google Play. So I think this assertion should be removed or they should prevent to call the assertion after the service was killed. They missed a lot of possibilities of the lifecycle. – Kimi Chiu Nov 25 '17 at 04:23
  • 3
    new Notification() throws an error for Android Version 27. Now you need to provide a valid notification – suku Dec 12 '17 at 10:35
  • You don't want to `startForeground` in `onCreate()`. It is better in `onStart()` because you can pass intent actions to it. – IgorGanapolsky May 15 '20 at 18:07