[英]Public class with only public static members
我有一個僅包含公共靜態成員的公共類。
我知道這不是最好的事情,但是我只是想知道為什么在我的Android上,如果我暫停應用程序,打開其他幾個並返回我的列表,那么所有變量似乎都是(null)。
問題:
這是我的代碼:
public class Session {
public static String ID = null;
public static String UNIQID = null;
public static String TOKEN = null;
public static String SESSIONID = null;
}
由於您的應用程序進程隨時可能被破壞,因此那些靜態實例實際上可能會被垃圾回收。
如果將這些靜態變量放在自定義的Application對象中,則除非將它們在每次(重新)創建應用程序時在應用程序的onCreate函數中進行初始化,否則它們將適用。
您應該使用SharedPreferences或SQLite數據庫來跟蹤持久性數據。
如果這些變量太復雜而無法像這樣存儲,那么您可能要考慮使用單例(不像以前那樣建議使用子類化Application)。
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;
}
是的,Android可能會在需要時收集內存
可能類似於SharedPreferences
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.