I have a public class that only contains public static members.
I know this is not the best thing to do but I was just wondering why on my Android, if I pause the application, open a few others and come back to mine, all variables seems to be (null).
Questions:
Here is my code:
public class Session {
public static String ID = null;
public static String UNIQID = null;
public static String TOKEN = null;
public static String SESSIONID = null;
}
As your application process might get destroyed any time, those static instances might get garbage collected indeed.
If you put these static variables in a custom Application object, same will apply, unless you initialise them in the application's onCreate function each time the application gets (re-)created.
You should keep track of persistent data using either SharedPreferences or a SQLite database.
If these variables are too complex to be stored like that then you might want to consider using a singleton (subclassing Application is not as recommended as it used to be).
public class MySingleton {
public static MySingleton getInstance(Context context) {
if (instance==null) {
// Make sure you don't leak an activity by always using the application
// context for singletons
instance = new MySingleton(context.getApplicationContext());
}
return instance;
}
private static MySingleton instance = null;
private MySingleton(Context context) {
// init your stuff here...
}
private String id = null;
private String uniqueId= null;
private String token = null;
private String sessionId = null;
}
Yes, android may collect memory when required
May be something like SharedPreferences
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.