Context.startForegroundService() did not then call Service.startForeground()

NiceGuy picture NiceGuy · Jun 8, 2017 · Viewed 169.4k times · Source

I am using Service Class on the Android O OS.

I plan to use the Service in the background.

The Android documentation states that

If your app targets API level 26 or higher, the system imposes restrictions on using or creating background services unless the app itself is in the foreground. If an app needs to create a foreground service, the app should call startForegroundService().

If you use startForegroundService(), the Service throws the following error.

Context.startForegroundService() did not then call
Service.startForeground() 

What's wrong with this?

Answer

zhuzhumouse picture zhuzhumouse · Jul 12, 2017

From Google's docs on Android 8.0 behavior changes:

The system allows apps to call Context.startForegroundService() even while the app is in the background. However, the app must call that service's startForeground() method within five seconds after the service is created.

Solution: Call startForeground() in onCreate() for the Service which you use Context.startForegroundService()

See also: Background Execution Limits for Android 8.0 (Oreo)