【发布时间】:2014-03-06 15:27:25
【问题描述】:
我有兴趣将我的数据保存在共享首选项中并从中加载数据。我想知道一个正确的方法:
我认为 Activity 类的情况很清楚,android 提供了 onCreate 和 onDestroy,我们应该在其中保存和加载首选项。我希望我没有错:)
但是如果我有一些像这样从 Object 派生的类
public class LoggerSingleton {
// Constants
private static final String LOG_FILE = "log";
private static final Integer MAX_LINES = 200;
// Variables
private static List<String> logsList;
private static Context appContext;
// class initialization is called first time you call getInstance
private static LoggerSingleton instance = new LoggerSingleton();
public static LoggerSingleton getInstance() {
return instance;
}
// Constructor
private LoggerSingleton() {
logsList = new ArrayList<String>();
appContext = MyApplication.getContext();
SharedPreferences settings = appContext.getSharedPreferences(LOG_FILE, Context.MODE_PRIVATE);
try {
JSONArray jsonArray = new JSONArray(settings.getString(LOG_FILE, "[]"));
for (int i = 0; i < jsonArray.length(); i++)
logsList.add(jsonArray.getString(i));
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getLogs() {
return logsList.toString();
}
public static void appendLog(String newLog) {
String currentDateandTime = Utils.getMyDateTime();
newLog = currentDateandTime + "_" + newLog;
Log.d(appContext.getString(appContext.getApplicationInfo().labelRes), newLog);
logsList.add(newLog);
while (logsList.size() > MAX_LINES)
logsList.remove(0);
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < logsList.size(); i++)
jsonArray.put(logsList.get(i));
SharedPreferences settings = appContext.getSharedPreferences(LOG_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(LOG_FILE, jsonArray.toString());
editor.commit();
}
}
我在 MyApplication 构造函数中调用 getInstance()。
我的问题是,我的对象是什么时候创建的,什么时候被销毁的?如何捕捉破坏事件?如何将我的字符串列表正确保存到共享首选项中?
我想涵盖所有情况:当操作系统将我的对象破坏为长时间未使用时,当用户执行“强制停止”并重新启动应用程序时,当手机进入关机状态并返回时。
我想我知道活动会发生什么,但是像这样的类和它的数据会发生什么?从 Application 派生的类会发生什么,当它被销毁时,它的数据会丢失吗?从 BroadcastReceiver 派生的类也是如此。是否有一些通用方法可以将所有这些类的数据保存到首选项中?
【问题讨论】: