The easiest way is to save data in onPause()
and restore it in onResume()
. Next question is where to store data. The are few way to do that:
- Using custom application context
You can extend android.app.Application
and register your class in your manifest file by
<application android:name="your.application.class" ...
This will allow you to get singleton instance of your class by calling `Context.getApplicationContext().
For an example you can create
public class MyContext extends Application {
Bundle mySavedData = null;
public void setSavedData(Bundle data){
mySavedData = data;
}
public Bundle getSavedData() {
return mySavedData;
}
}
and then use it like this
@overide
public void onResume(){
...
Bundle state = ((MyContext) getApplicationContext()).getSavedData();
if(state != null) {
/* restore states */
}
...
}
@overide
public void onPause(){
...
Bundle state = new Bundle();
...
/* save your data here and save it into the context or set null otherwise*/
((MyContext) getApplicationContext()).setSavedData(state);
...
}
- Using singleton pattern
Instead of defining context you can create singleton instance
public class MySingleton {
static MySingleton instance;
public static MySingleton getInstance() {
if(instance == null){
instance = new MySingleton();
}
return instance;
}
public Bundle mySavedData = null;
void setSavedData(Bundle data){
mySavedData = data;
}
public Bundle getSavedData() {
return mySavedData;
}
}
and you can use it
@overide
public void onResume(){
...
Bundle state = MySingleton.getInstance().getSavedData();
if(state != null) {
/* restore states */
}
...
}
@overide
public void onPause(){
...
Bundle state = new Bundle();
...
/* save your data here and save it into the context or set null otherwise*/
MySingleton.getInstance().setSavedData(state);
...
}
Be aware that context and singletons are destroyed if application is killed. If you want to store your data permanently than using application document folder or database if recommend but I think that isn't what you looking for.
I hope this will help you....