I have been reading the Android documentation and I am wondering if anyone can shed some light on what happens to a service instance when a service started with START_STICKY has it's process killed. I am assuming that the local state data (instance variables) are also lost. Does Android do anything to help re-populate the local state when it recreates the service?
I had some data that was sent to the service in an intent. In onStateCommand(), I would populate the service's instance data based on what was in the intent. From what I have read in the Android docs, the intent passed to onStartCommand() will be null when the service has been killed and restarted (with START_STICKY). Does this mean that I lose both the intent and the service's member data when the service is recreated?
Constant to return from onStartCommand(Intent, int, int) : if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int) ), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int) .
START_STICKY- tells the system to create a fresh copy of the service, when sufficient memory is available, after it recovers from low memory. Here you will lose the results that might have computed before. START_NOT_STICKY- tells the system not to bother to restart the service, even when it has sufficient memory.
You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.
Sticky Services — Sticky service is somewhere between regular service and foreground service Android will kill the process time to time of this service, however it will be created automatically if the resources are available as soon as possible.
When a process is killed and recreated, it goes through the entire lifecycle again (starting at onCreate). Depending on how it was killed and how you save data it may or may not be available to you.
As for getting the intent back, there's a flag for START_REDELIVER_INTENT
that will redeliver the intent.
I recently came across this same problem. Service provides no built in means of saving state and the last intent may not be enough to get the service back to its previous state. My solution was to have the activity persist state and pass that state to the service via startService(). The service then just fires events at the activity, like:
This approach cleaned up my design a lot, and both service and activity are resilient to being killed.
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