恢复后数据丢失如何处理

How to handle data missing after resume

我在开发应用程序时遇到了一些问题。

在我最小化应用程序或关闭屏幕后,打开很多其他应用程序或在很长时间后重新打开phone。 当我重新启动我的应用程序时,它会尝试恢复并继续显示相同的页面(带有片段)。 但是我需要的数据已经被销毁了,所以它会是空的。 数据是一个对象数组,我知道也许我可以将它们存储在数据库中。 但是由于每次用户单击某些内容时数据都会更新。 所以我不想将它保存到数据库中,我想这意味着不需要大量存储 I/O 。 我想知道当东西被破坏时是否有任何解决方案可以重新启动 hole 应用程序? 或者实现它的唯一方法是我处理空数组并自己重新加载? 我真的不想这样做,因为我想这会给我带来很多意想不到的问题,因为数据与许多页面相关。 翻页时需要考虑的情况太多了。

有什么建议吗?

But the data I need was already been destroyed so it will be null

那是因为your process was terminated and you did not save your state.

But due to the data will update every time user click something

或者,您可以创建一个线程来将数据保存为 onPause()onStop() 方法的一部分。 "never save"和"save on every click"之间有很多可能。

So I don't want to save it into data base, I guess that means lot of storage I/O witch is not necessary

如果您希望数据在用户离开应用后 30 分钟以上仍存在,您的选择是将数据保存在本地(文件、数据库、SharedPreferences)或将数据保存在 Internet 上的某处.

对于较短时间段内的少量数据,您可以将数据放入提供给 onSaveInstanceState()Bundle 中,稍后再将数据从 Bundle 中拉出(例如,在 activity 的 onRestoreInstanceState() 中)。您已经应该这样做来处理屏幕旋转和其他配置更改。

I'm wondering if there is any solution to restart the hole app when things is destroyed?

欢迎您使用 add android:clearTaskOnLaunch="true" to your launcher activity, to indicate that you always want to start over from scratch whenever the user leaves your app and tries to come back to it. Users will not appreciate this, as this means that they will lose their state even for being out of your app briefly (e.g., a quick reply to a text message). This attribute does not terminate your process, but it will force the user back to the launcher activity,这将消除您应用中之前的任何其他活动。

Or the only way to make it happen is I handle the null array and do the reload myself?

这是开发人员通常做的,是的。