在ApplicationContext中存储对象

Har*_*n R 9 android

当我的应用程序转到后台时,我的(静态和单例)对象被清除.所以我尝试将这些对象存储在Applicaton Context中.我使用以下代码.

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

在应用程序上下文中存储对象是否可行(可靠)?我不确定以下方式是否正确.请指导..

   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;
            }

        }
Run Code Online (Sandbox Code Playgroud)

请帮忙.

pan*_*wal 12

您应该知道,如果在后台长时间不使用应用程序上下文本身就会被破坏.因此,当应用程序处于后台时,无法保证您的静态和单例对象不会被清除.相反,您可以做的是不时地持久保存您的对象(在平面文件或共享首选项或数据库中)并onCreate在Application类的方法中恢复它们