Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

START_STICKY for Foreground Services

A Foreground Service has a very high priority and is very unlikely to be killed by the system, so is there any point in returning START_STICKY in onStartCommand?

Edit: This question is not about the difference between START_STICKY and START_NON_STICKY, it's about the usability of START_STICKY in relation to Foreground Services.

like image 520
Florian Walther Avatar asked May 08 '18 13:05

Florian Walther


People also ask

What does it mean app is using foreground service?

Foreground services perform operations that are noticeable to the user. Foreground services show a status bar notification, so that users are actively aware that your app is performing a task in the foreground and is consuming system resources.

Can foreground service be killed by Android?

The Android system stops a service only when memory is low and it must recover system resources for the activity that has user focus. If the service is bound to an activity that has user focus, it's less likely to be killed; if the service is declared to run in the foreground, it's rarely killed.

What is Start_sticky?

START_STICKY means the system will eventually restart your Service after it has been killed by the system. When it gets restarted, the Intent parameter to onStartCommand() will be null. This lets you detect when you get restarted as the Intent will otherwise be the one you passed to startService().


1 Answers

"is very unlikely to be killed" != "will never be killed". For example, the user can terminate your process through a variety of means.

If you care about those scenarios and want to have your service be restarted (when eligible), use START_STICKY or START_REDELIVER_INTENT. If you are happy to let the service stay dead, use START_NOT_STICKY.

For example, if you are writing a music player, return START_NOT_STICKY, as it may not be appropriate for your app to start playing music at some arbitrary time later when the system elects to restart your service.

like image 71
CommonsWare Avatar answered Oct 10 '22 01:10

CommonsWare