且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android的保存的onPause或游戏的onDestroy状态?

更新时间:2023-02-02 19:26:51


  

尽管这样,我找不到任何地方推荐给保存状态的onDestroy()和每个人似乎都用的onPause建议。我缺少一条信息在这里?


块引用>

您是:)。 的onDestroy()不能保证被调用。请参见它的文档


  

注意:不要在这个方法被称为保存数据的地方算!例如,如果一个活动是在内容提供商编辑数据,这些编辑内容应在任一的onPause()或的onSaveInstanceState(包),而不是在这里提交。的这种方法通常实现为***资源,例如那些关联的线程与活动,使破坏活动不会乱放,而其应用程序的其余仍在运行这样的事情。的在有些情况下,系统只会杀死活动的托管过程中无需调用它的这个方法(或任何其他人),因此它不应该被用来做打算事情的过程后仍然四处消失。


块引用>

I am trying to implement a 'resume' feature for a game I'm developing. It should work as follows:

  • If the user starts a game and later closes the game with finishing, the game state is saved. When opening the app again, a 'resume' option will be available.

  • If the activity is only paused (e.g. minimized due to a phone call) and the user returns, it should show the game in progress. It should not terminate and save the state, unless of course, the OS decides to kill the activity.

I've decided to use SharedPreferences for the most part, as well as a custom file to save extra information. I've seen a lot of people recommend saving the state of the program in the onPause() method and I've been wondering why this is the case.

From what I can gather, using OnDestroy() would be better. onPause() does not mean the activity will be killed so I could be wasting time when saving the game state necessarily. I've checked my program and onDestroy() is being called at the appropriate times. I'm assuming therefore I have no leak keeping the activity from being destroyed.

Despite this, I cannot find anywhere recommending to save state in onDestroy() and everyone seems to recommend using onPause. Am I missing a piece of information here?

Despite this, I cannot find anywhere recommending to save state in onDestroy() and everyone seems to recommend using onPause. Am I missing a piece of information here?

You are :). onDestroy() is not guaranteed to be called. See the documentation for it:

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.