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

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?

31 Answers
31

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)

Leave a Comment