onSaveInstanceState()和onPause() [英] onSaveInstanceState() and onPause()

查看:69
本文介绍了onSaveInstanceState()和onPause()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Android中的这两种方法有些困惑.

I'm a little bit confused about these two methods in Android.

从文档中我了解到,应该调用onSaveInstanceState()来仅存储临时信息,并且应该使用onPause()来存储任何持久性数据.

From the documentation I understand that onSaveInstanceState() should be called to store only temporary information, and onPause() should be used to store any persistent data.

我想知道为什么每次调用onPause()时都根本要调用onSaveInstance().然后,我在记事本教程中阅读:

I was wondering why to call onSaveInstance() at all, when onPause() is called every time. Then I read in the Notepad tutorial:

"请注意,saveState()必须为 在两个onSaveInstanceState()中都被调用 和onPause()来确保 数据已保存.这是因为 不能保证 onSaveInstanceState()将被调用 因为当它被调用时,它是 在onPause()之前调用."

"Note that saveState() must be called in both onSaveInstanceState() and onPause() to ensure that the data is saved. This is because there is no guarantee that onSaveInstanceState() will be called and because when it is called, it is called before onPause()."

不能保证将调用onSaveInstanceState(),因为您可以使用后退"按钮简单地退出活动.

There is no guarantee that onSaveInstanceState() will be called because you can simply walk out of the activity using the back button.

但是据此,如果您不将持久性数据保存在这两种方法中,则该应用程序可能在onSaveInstanceState()中时被杀死.

But according to this if you don't save the persistent data inside both methods, the app might be killed while inside onSaveInstanceState().

所以我们实际上需要在这两种方法中保存持久性数据,对吗?

So we need to save the persistent data in both methods actually, am I right?

但是,如果这是真的,不是那么多的开销,也许应该有一些其他的附加标志来告知该方法是否已被调用或其他内容?

But if this is true, isn't this too much of an overhead and maybe there should be some other additional flag to tell if the method is already called or something?

http://developer.android.com/resources/tutorials/notepad/notepad-ex3.html

推荐答案

从开发人员指南上活动:

注意:由于不能保证调用 onSaveInstanceState(), 您只应使用它来记录活动的暂时状态 (UI的状态)—永远不要使用它来存储持久性 数据.相反,您应该使用 onPause()存储持久数据(例如 作为应保存到数据库的数据),当用户离开 活动.

Note: Because onSaveInstanceState() is not guaranteed to be called, you should use it only to record the transient state of the activity (the state of the UI)—you should never use it to store persistent data. Instead, you should use onPause() to store persistent data (such as data that should be saved to a database) when the user leaves the activity.

这篇关于onSaveInstanceState()和onPause()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆