问题
I have created an android app in which i'm using an application class to store and access the global variables. But i came across a strange behavior that all the variables in my application class gets uninitialized in the following scenarios,
- if my app is idle for sometime(say 10 minutes or so).
- if my app goes to background (if a browser gets opened above the app).
I searched a lot in SO and web and doesn't found any suitable answer. AFAIK once application class is initialized it will be accessible for the lifetime of the application. Am i missing something here?
Since i'm new to android development i may be doing something wrong here. Can anyone point me to the right direction?...Thanks in advance.
public class MyApp extends Application {
private MyClass classObj = new MyClass();
private boolean flagOne = true;
private boolean flagTwo = false;
void setFlagOne(boolean flag) {
flagOne = flag;
}
boolean getFlagOne() {
return flagOne;
}
void setFlagTwo(boolean flag) {
flagTwo = flag;
}
boolean getFlagTwo() {
return flagTwo;
}
void setMyClassObj(MyClass obj) {
classObj = obj;
}
boolean getMyClassObj() {
return classObj;
}
}
回答1:
At last i got it sorted out by saving the variable state using shared preferences and storing the object in application files directory. So if the application recreates at any time (sometimes if the app goes in background) i restore the state of the variables and read the object back. So the variables don't go uninitialised at an point of time.
Storing values,
SharedPreferences pref = getSharedPreferences("appstate", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putBoolean("flagone", flagOne);
editor.putBoolean("flagtwo", flagTwo);
Retrieving values,
SharedPreferences pref = getSharedPreferences("appstate", Context.MODE_PRIVATE);
flagOne = pref.getBoolean("flagone", true);
flagTwo = pref.getBoolean("flagtwo", false);
来源:https://stackoverflow.com/questions/24060862/application-class-variables-gets-uninitialised-in-android