Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: When a service is killed, how can we persist the service state for later restoration?

We have created an app that is essentially a timer/stopwatch with some decked out features. We defined a service that ticks the clock and alerts listeners (activities, etc.) who are subscribed to certain timer events.

We would like to be able to save the state of the timer/stopwatch (elapsed seconds, time until next event, user-provided config etc.) whenever android kills our service (for memory recollection), and then restore the state of the service when the app is restored by the user. For us, this means possibly preserving and restoring objects and their state. We have lots of composition in our service. Basically, our service is composed of all our timer models, of which die when the service dies.

What strategies are there to persist the state of the service? PreferencesManager probably isn't robust enough for our purposes, though it might be. Can we rely on the Service onDestroy() method to save state (say in SQLite)? If android decides to kill our process, is it even guaranteed that the service onDestroy() will be called?

Thank you!

like image 478
Walt Dizzy Records Avatar asked Oct 16 '13 19:10

Walt Dizzy Records


1 Answers

We defined a service that ticks the clock and alerts listeners (activities, etc.) who are subscribed to certain timer events

You do not need to have a service running all the time, watching the clock tick. This approach is user-hostile, as it ties up system RAM for no good reason. Use AlarmManager to get control at "certain timer events", and keep your service out of memory for the rest of the time.

We would like to be able to save the state of the timer/stopwatch (elapsed seconds, time until next event, user-provided config etc.)

Do not persist "elapsed seconds". Persist the time when the timer/stopwatch began. Elapsed seconds is then a matter of subtraction.

Do not persist "time until next event". Persist the time of the next event.

These values do not continuously change, and therefore can be persisted when the timers are started or other major lifecycle events in the life of the timer.

What strategies are there to persist the state of the service?

Use a database, SharedPreferences, or a file format of your own choosing.

Can we rely on the Service onDestroy() method to save state (say in SQLite)?

No.

If android decides to kill our process, is it even guaranteed that the service onDestroy() will be called?

It is not guaranteed to be called.

like image 94
CommonsWare Avatar answered Nov 10 '22 01:11

CommonsWare