Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save/restore global variables in android even when os kill application

In android,Google recommends us to save the global variables in Application. But there is a problem, if the android os kill the application because of low of memory, the application will be re-oncreate and the global variables I saved will be lost.

I don't know when to save/restore these variables,application doesn't give us some methods such as onsaveinstancestate()/onrestoreinstancestate().

I have one idea but I can't make sure it can work well. I see some app will go to slashScreen when os killed it, maybe we can save these gloabl variables in SplashAvtivity? Because Activity has the methods onsaveinstancestate()/onrestoreinstancestate(), app start splashActivity at first and don't finish it, when we find os kill the app, we can go to SplashActivity(finish all activity upon it in task) again then onrestoreinstancestate().

Is there any other good way to save/retore the global variables? Of course, I think if google can offer us a method such as onsaveinstancestate()/onrestoreinstancestate() in application, it will be better.:S

like image 434
small_dream Avatar asked Nov 05 '13 06:11

small_dream


2 Answers

If a variable must persist between executions, you have to do some disk persistence. The easiest way, as suggested by Raghunandan, is using Shared Preferences.

To do this, first request a shared preferences:

SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key_name", "key_value");
editor.commit(); //important, otherwise it wouldn't save.

You can do this, for instance, in the onStop or onPause of the activity (onPause is always called, but there's no guarantee onStop will be called prior to Honeycomb).

In your onCreate (or when you need the value), you read from SharedPreferences and check if there's a value set, otherwise use a default value:

SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
String myVariable = prefs.getString("key_name", "default_value");

Now you can use myVariable with the persisted value or the initial (default) value if nothing was saved before.

For more, see https://developer.android.com/guide/topics/data/data-storage.html#pref

To clarify, PREFS_NAME is the name of your shared preferences file. Usually, prepend the package name for your application, it's good practice.

like image 140
Douglas Drumond Kayama Avatar answered Jan 18 '23 23:01

Douglas Drumond Kayama


As per new guidelines always Consider using apply() instead of commit on shared preferences. Whereas commit blocks and writes its data to persistent storage immediately, apply will handle it in the background and will not hamper your other ongoing work.

like image 24
Arpit J. Avatar answered Jan 19 '23 00:01

Arpit J.