保存应用程序状态应用程序、状态

2023-09-06 22:33:46 作者:薇薇安

作为一个从我的活动之间共享状态的问题,怎么能保存我的应用程序的实例状态?由于应用程序不延活动,没有的onSaveInstanceState 方法覆盖。

As a follow on from my question on sharing state between Activities, how can I save the instance state of my Application? Since Application does not extend Activity, there is no onSaveInstanceState method to override.

注意:在提前,这不是一个重复。尽管它的名字,如何保存一个Android应用程序的状态?涉及到活动状态的

NB: In advance, this is not a duplicate. Despite its name, How do I save an Android application’s state? relates to Activity state

推荐答案

您不能使用的 Application.onTerminate() ,因为谁也不能保证,这将是调用。

You can't use Application.onTerminate() since there's no guarantee that this will be called.

出于同样的原因原因你不能使用的onStop()的onDestroy()活动或者

For the same reason reason you can't use onStop() or onDestroy() from Activity either.

所以,你必须做你保存在的 的onPause() 在每一个活动的方法。每个活动将有一个呼叫 saveState和()您在应用程序所创建。因为这将让叫了很多,你需要使它尽可能高效,最好只写更改数据持久性存储。

So you'll have to do your save in the onPause() method in every Activity. Each Activity will have a call a saveState() you've created in your Application. Since this will get called a lot you will need to make it as efficient as possible, ideally only writing changed data to persistent storage.

您还应该注意的是的onSaveInstanceState()应仅用于存储的短暂的的活动的状态。例如,如果一个活动由用户pressing后退按钮结束的onSaveInstanceState()不叫。所以,即使你没有共享的状态,你仍然应该使用的onPause()来保存持久的改变。

You should also note that onSaveInstanceState() should be used only for storing the transient state of an Activity. For example, if an Activity is ended by the user pressing the Back button onSaveInstanceState() is not called. So even if you didn't have shared state, you should still be using onPause() to save persistent changes.