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?
Inside the service, usually in onStartCommand() , you can request that your service run in the foreground. To do so, call startForeground() . This method takes two parameters: a positive integer that uniquely identifies the notification in the status bar and the Notification object itself.
NO MORE STARTSERVICE - The new context. startForegroundService() method starts a foreground service but with a implicit contract that service will call start foreground within 5 second of its creation. You can also call startService and startForegroundService for different OS version.
Inside the onReceive() method I call stopforeground(true) and it hides the notification. And then stopself() to stop the service.
onStartCommand() The system invokes this method by calling startService() when another component (such as an activity) requests that the service be started.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With