简体   繁体   English

Android应用程序-保存状态

[英]Android application - saving state

I have my own Application class object where I store all application data. 我有自己的Application类对象,在其中存储所有应用程序数据。 In Application.onCreate I create all applications objects and read data from SharedPreferences. 在Application.onCreate中,我创建所有应用程序对象并从SharedPreferences中读取数据。 My problem is that when the application goes to background it may be killed. 我的问题是,当应用程序进入后台时,它可能会被杀死。 After I select the app from launcher, the activity stack is restored (the last Activity is launched, instead of Launcher Activity). 从启动器中选择应用程序后,将还原活动堆栈(启动最后一个活动,而不是启动器活动)。 The problem is the Application.onCreate is not called thus all applications objects are not loaded and I run into troubles. 问题是没有调用Application.onCreate,因此没有加载所有应用程序对象,并且遇到了麻烦。 WHat is the best way to store/restore Application data/object. WHat是存储/恢复应用程序数据/对象的最佳方法。 I know that it can be done in Activities.onCreate/onDestroy but I have many Activities in my app and do not know, which on them will be on top when the application is killed/restarted. 我知道可以在Activities.onCreate / onDestroy中完成此操作,但是我的应用程序中有很多Activity,并且不知道,当应用程序被终止/重新启动时,它们上的哪个活动将排在最前面。

Serialize your ApplicationObject and store it to a File (simple) or Object Store (complex) 序列化您的ApplicationObject并将其存储到文件(简单)或对象存储(复杂)中

or you can implement a Serialize / Deserialize functionality 或者您可以实现序列化/反序列化功能

Where , Serialize will convert object properties to JSON and store 在哪里,序列化会将对象属性转换为JSON并存储

DeSerialize will loads the JSON and populate the Object and returns. DeSerialize将加载JSON并填充Object并返回。

When you launch your application and it starts from the last activity and not from the launcher activity, it means that your application has not been killed. 当您启动应用程序时,它是从上一个活动而不是启动程序活动开始的,这意味着您的应用程序尚未被杀死。 So in this case, your application's onCreate method will not be called, because it is still alive. 因此,在这种情况下,将不会调用应用程序的onCreate方法,因为它仍然有效。

Application's onCreate method is called once during the lifecycle of the app. 在应用程序的生命周期中,将一次调用应用程序的onCreate方法。 So until your app class is alive, you should have all your application data accessible. 因此,在您的应用程序类别未激活之前,您应该可以访问所有应用程序数据。

If you need to test, what happens when your application has been killed, so you should go to the "application manager" and kill manually the app. 如果您需要测试,当您的应用程序被终止时会发生什么,因此您应该转到“应用程序管理器”并手动终止该应用程序。

EDIT: if your application is alive, as long as your application has a reference to the data, they can not be removed by gc. 编辑:如果您的应用程序还活着,只要您的应用程序具有对数据的引用,它们就不能被gc删除。 So, in your case, perhaps you forgot to update the data correctly. 因此,就您而言,也许您忘记了正确更新数据。 So serializing will not help you in this case, otherwise you will have bugs. 因此,在这种情况下,序列化将无济于事,否则您将遇到错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM