I’ve subclass Application to keep a global state in static variables. But if the application is leaved in the background, it is eventually getting killed, meaning my global state is lost.
I’ve tried to overcome this problem by subclassing Activity and override onSaveInstanceState to save the global state each time an Activity is destroyed and then recreate it when an Activity is created. This however, gives an non-negligible overhead each time an activity is created.
One could argue that if the application is killed the correct behaviour would be to let user start again from the first Activity, but as the application is killed quite often I don’t find this acceptable.
Is there a better approach? I’ve seen some suggestion to save the global state in shared preferences instead of static variables, but for some reason I don’t find that solution compelling.
onSaveInstanceState is for “interruptions” where the activity / is destroyed while the user is interacting. You should save small state information there, e.g. entered text for visible views (EditText, …). Examples when this happens are: rotating the device (the activity is destroyed and recreated), incoming calls, …
If the user does not interact with the application for some time you should save the state permanently. I recommend to use SharedPreferences or a database in this case. It’s a bit more work, but it is the best solution in my opinion.