【问题标题】:Android lifecycle of classes and data, Object, Application, BroadcastReceiver类和数据、Object、Application、BroadcastReceiver的Android生命周期
【发布时间】: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 派生的类也是如此。是否有一些通用方法可以将所有这些类的数据保存到首选项中?

【问题讨论】:

    标签: android object lifecycle


    【解决方案1】:
    public class MyApplication extends Application {
    
    @Override
    public void onCreate() {
        super.onCreate();
        LoggerSingleton.initLoggerSingleton(getApplicationContext());
    }
    

    }

    在应用程序中初始化你的单例类(应用程序上的初始化已启动) 在 YourApplication 中初始化对象后(扩展应用程序) 您可以从应用程序中的任何活动访问它 如果应用程序在嵌套启动时被操作系统杀死,它将重新初始化你的单例

    课堂上的小变化

    public class LoggerSingleton {
    // Constants
    private static final String LOG_FILE = "log";
    private static final Integer MAX_LINES = 200;
    
    // Variables
    private List<String> logsList;
    private Context appContext;
    
    // class initialization is called first time you call getInstance
    private static LoggerSingleton instance ;
    
    public static LoggerSingleton getInstance() {
        return instance;
    }
    public static void initLoggerSingleton(Context context){
        if(instance==null)
            instance = new LoggerSingleton(context);
    }
    
    // Constructor
    private LoggerSingleton(Context context) {
        logsList = new ArrayList<String>();
        appContext = context;
    
        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 String getLogs() {
        return logsList.toString();
    }
    
    public 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();
    }
    

    }

    之后,您可以从活动或不同的班级访问您的单身人士

    public class MainActivity extends Activity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
    
        LoggerSingleton.getInstance().appendLog("String");
    
    
    
    }
    

    }

    在 Activity 调用 onStop 和读取 onStart/onResume 时保存数据的最佳方法

    当活动调用 onDestory 方法时,操作系统将您的应用程序从进程中删除,如果操作系统需要更多内存,则从操作系统中删除

    关于将你的arrayList保存在sharedPref Saving Serializable Objects List into sharedPreferences

    【讨论】:

    • 感谢您的回答。我对这种情况很感兴趣:我的活动被破坏了,我的广播接收器获取了一些数据,它需要将它们存储在某个地方。因为用户可以强制停止应用程序然后再次打开它。在这种情况下你有什么建议?
    【解决方案2】:

    你可以试试这样 不确定这样做是否正确并且不对其进行测试

    public class IntentReceiver extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
        LoggerSingleton.initLoggerSingleton(context);
        LoggerSingleton.getInstance().appendLog("String");
    
    }
    

    }

    BrodcatsReceiver 有一个 onReceive 方法,他在其中获取 Context 尝试初始化你的单例类并保存你的数据

    附:不确定保存从广播接收器恢复的日期是否正确的方法从不测试它尝试读取BroadcastReceiver

    【讨论】:

      猜你喜欢
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多