当应用程序被强行杀死时调用 LifeCycles

LifeCycles getting called when app is forcefully killed

我在我的应用程序中使用 onDestroy 方法来清理数据。

Google 的文档说 documentation

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

这种情况是将应用从最近的任务列表中滑出。

所以在这种情况下,数据和其他用户重要信息必须保存在onPause或orStop()中。

但是根据这个 ,none 个生命周期被调用。

那么我们将数据保存在哪里?

But according to this link, none of the lifecycles get called.

这个答案有点误导。当用户调出概览屏幕(最近的任务列表)时,您的前景 activity 不应再出现在前景中。结果,onPause()onStop() 将在 activity 上被调用。您可以通过覆盖 onPause()onStop() 并记录它们的调用来对此进行测试。

So where do we save our data?

这在很大程度上取决于您正在构建什么。

在某些情况下,当数据发生变化并且用户表示他们想要保留此数据时保存数据。

在某些情况下,定期保存数据。例如,在游戏中,您可能会经常保存游戏状态,以便用户可以从他们离开的地方继续游戏。

在某些情况下,使用生命周期方法(例如,onStop())作为数据保存触发器可能没问题,但有时则不行。说 "we will save the stuff that the user has typed in when we get called with onStop()" 可能没问题。说 "we will go ahead and charge the user's credit card when we get called with onStop()" 可能不太好。