Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 920
NiceGuy Avatar asked Jun 08 '17 02:06

NiceGuy


People also ask

What is startForeground in Android?

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.

What is the difference between startService and startForegroundService?

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.

How do you stop foreground service?

Inside the onReceive() method I call stopforeground(true) and it hides the notification. And then stopself() to stop the service.

Which of the following methods is invoked when another component requests the service to be started by calling the startService () method?

onStartCommand() The system invokes this method by calling startService() when another component (such as an activity) requests that the service be started.


1 Answers

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)

like image 131
zhuzhumouse Avatar answered Nov 21 '22 23:11

zhuzhumouse