在ApplicationContext中存储对象对象、ApplicationContext

2023-09-06 09:54:18 作者:Melancholy惆怅

在我的应用程序被切换到后台,我的(静态和单身)对象被清除。 于是,我就来存储这些对象的的一个应用上下文。我现在用的是下面的code。

When my application goes to background , my (static and singleton) objects are cleared. So I tried to store these objects in Applicaton Context . I am using the following code.

Accounts.create(getApplicationContext())将被调用一次来存储帐户的实例。

Accounts.create(getApplicationContext()) will be called once to store the accounts instance.

这是可能的(可靠)的应用程序上下文来存储对象?我不知道下面的路是正确与否。请指导..

Is that possible(reliable) to store objects in Application Context ? I am not sure the following way is correct or not . please guide ..

   public class Init extends Application {
    private Hashtable<Object, Object> globalStore = new Hashtable<Object, Object>();

    public void putToGlobalStore(Object key, Object value) {
        globalStore.put(key, value);
    }

    public Object takeFromGlobalStore(Object key) {
        return this.globalStore.get(key);
    }

    public void removeFromGlobalStore(Object key) {
        this.globalStore.remove(key);
    }

    public boolean containsInGlobalStore(Object key) {
        return this.globalStore.containsKey(key);
    }
}

public class Accounts {

        protected Accounts(String name, Context context) {
            Init init = (Init) applicationContext;
                init.putToGlobalStore(name, this);
        }

        private static Init applicationContext;

        public static void create(Context context) {

            if (context instanceof Application)
                applicationContext = (Init) context;
            else
                applicationContext = (Init) context.getApplicationContext();

            if (applicationContext.containsInGlobalStore(GLOBAL_NAME))
                Logger.log("Warning " + GLOBAL_NAME
                        + " is already created. This will remove all old datas");

            new Accounts(GLOBAL_NAME, applicationContext);


        }

        private static final String GLOBAL_NAME = "accounts";

        public static Accounts getInstance() {

            try {
                return (Accounts) applicationContext
                        .takeFromGlobalStore(GLOBAL_NAME);
            } catch (Exception e) {
                Logger.log("GLOBAL_NAME Lost");
                return null;
            }

        }

请帮忙。

推荐答案

您应该知道,应用程序上下文本身被破坏,如果闲置了很长一段时间的背景。因此,有没有保证,当应用程序在后台静态和单一对象不会被清除。相反,你可以做的就是坚持从时间的对象时(无论是在平面文件或共享preference或数据库),并在的onCreate 方法恢复它们Application类

You should know that the application context itself gets destroyed if left unused for a long time in the background. So there is no guarantee that your static and singleton objects will not be cleared when the app is in background. Instead what you can do is persist your objects from time to time (either in a flat-file or shared preference or database) and restore them in the onCreate method of the Application class