Search code examples
androidandroid-serviceandroid-8.0-oreo

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent


On application launch, app starts the service that should to do some network task. After targeting API level 26, my application fails to start service on Android 8.0 on background.

Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=my.app.tt/com.my.service }: app is in background uid UidRecord{90372b1 u0a136 CEM idle procs:1 seq(0,0,0)}

as I understand it related to: Background execution limits

The startService() method now throws an IllegalStateException if an app targeting Android 8.0 tries to use that method in a situation when it isn't permitted to create background services.

"in a situation when it isn't permitted" - what it's actually mean?? And how to fix it. I don't want to set my service as "foreground"


Solution

  • The permitted situations are a temporary whitelist where the background service behaves the same as before Android O.

    Under certain circumstances, a background app is placed on a temporary whitelist for several minutes. While an app is on the whitelist, it can launch services without limitation, and its background services are permitted to run. An app is placed on the whitelist when it handles a task that's visible to the user, such as:

    • Handling a high-priority Firebase Cloud Messaging (FCM) message.
    • Receiving a broadcast, such as an SMS/MMS message.
    • Executing a PendingIntent from a notification.
    • Starting a VpnService before the VPN app promotes itself to the foreground.

    Source: https://developer.android.com/about/versions/oreo/background.html

    So in other words if your background service does not meet the whitelist requirements you have to use the new JobScheduler. It's basically the same as a background service, but it gets called periodically instead of running in the background continuously.

    If you're using an IntentService, you can change to a JobIntentService. See @kosev's answer below.