在Android上保持应用程序状态 [英] Keep application state on android

查看:72
本文介绍了在Android上保持应用程序状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在保存应用程序的状态/单身时遇到了麻烦.

I am having trouble saving the state/singleton of my application.

当应用程序启动时,将显示加载屏幕(活动),并使用来自Web服务调用的值初始化单例(请注意,网络访问无法在主线程上运行).

When the application starts a loading screen (activity) is shown and a singleton is initialized with values from a webservice call (note that network access cannot run on the main thread).

创建单例之后,我打开我的主要活动.请注意,单例中的值是构建布局所必需的.

After the singleton is created I open my main activity. Note that values from the singleton are required to build the layout.

现在假设该应用在后台运行并在后台被杀死(例如,由于内存不足).应用被杀死后,我的单例实例被删除.当我切换回我的应用程序时,它将尝试重新创建主要活动.如前所述,单身人士的值是构建布局所必需的,因此会导致NullPointerException(当我尝试访问单身人士的成员时,因为不再存在).

Now assume the app goes in the background and is killed there (e.g. because of low memory). My singleton instance is deleted as the app is killed. When I switch back to my app it tries to recreate the main activity. As I mentioned earlier the values from the singleton are required to build the layout, so this leads to a NullPointerException (when I try to access members of the singleton, as it is not there anymore).

我可以以某种方式告诉android在应用被杀死后开始第一个加载活动吗?如果可以在重新创建布局之前刷新单例,那就太好了,但这似乎是一个问题,因为网络调用不能在主线程上,因此在刷新完成之前就不会阻塞.我以为我可以将单例保存在所有活动onStop中,然后在onCreate方法中重新创建它,但这似乎有点不可预测,并且可能导致状态不一致...

Can I somehow tell android to start the first loading activity after the app was killed? It would be great if I could refresh the singleton before the layout is recreated, but this seems to be a problem as network calls can not be on the main thread and therefore not block until the refresh is finished. I assume that I could save the singleton in all activities onStop and recreate it in the onCreate methods, but this seems a bit too unpredictable and would probably lead to a inconsistent state...

另一种方法可能是始终在onStop上完成我的活动,但这会导致用户最后失去哪个标签,依此类推,即使该应用没有被杀死,因此也不是一个好选择.

Another way could be to just always finish my activity onStop, but this would lead to losing on which tab the user last and so on, even if the app is not killed, so this is not a good option.

关于如何解决此问题的任何想法?

Any ideas on how to solve this?

推荐答案

为什么不只使用SharedPreferences而不是单例呢?

Why not just use a SharedPreferences instead of a singleton?

任何时候您要保存一些全局状态,请将其提交给首选项.每当您想读取全局状态时,都可以从首选项中读回它.

Anytime you want to save some global state, commit it to preferences. Anytime you want to read the global state, read it back from preferences.

那么您完全不必担心应用程序的生命周期,因为无论手机在做什么,您的数据都将始终被保留.

Then you don't have to concern yourself with application lifecycle at all, as your data will always be preserved regardless of what the phone is doing.

这篇关于在Android上保持应用程序状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆