android - onCreate 和 onRestoreInstanceState 是互斥的吗?

标签 android

我有几个关于 onRestoreInstanceStateonSaveInstanceState 的问题。

1) 这些方法在哪里适合 Activity 生命周期?我已经阅读了很多文档,但没有明确的想法,除了一个广泛的声明,即何时保存 Activity 的状态

2) onCreateonRestoreInstanceState 是否互斥?

3) Activity 销毁时是否调用 onRestoreInstanceState?这是什么意思?一个 Activity 总是被销毁,除非另一个 Activity 漂浮在当前之上。

4) onRestoreInstanceState 似乎只能从果冻 bean 中的仪器调用。这不再与 Activity 生命周期相关吗?

最佳答案

where do these methods fit the activity lifecycle?

OnSaveInstanceState 在您的 Activity 即将被终止或重新启动之前调用(例如内存压力或配置更改的 b/c)。请注意,这与 onPause 不同,后者在您的 Activity 失去焦点时调用(例如,您转换到另一个 Activity)。

通常 onSaveInstanceState 将在 onPause 之后但在 onStop 之前调用,但并非总是如此。例如,如果您按回,则 Activity 被破坏(如调用完成())并且不需要保存状态,因此不会调用 onSaveInstanceState。那么为什么不在 onPause 中保存状态呢?仅仅因为 Activity 失去焦点并不意味着它已被杀死。它仍在内存中。基本上,您不想在每次暂停时保存状态,而是在您暂停并即将变得不可见时(即从前台转到后台)。

那么在 onPause 中你应该做什么呢?理想情况下,您应该释放消耗电池的资源,例如网络连接、关闭地理或加速度计、暂停视频(所有这些都取决于您的应用程序)。并在 onResume 中恢复这些资源,正如您可能已经猜到的,当您的 Activity 获得焦点时,它会被调用。

Are onCreate and onRestoreInstanceState mutually exclusive?

onRestoreInstanceState 是多余的,因为您可以在 onCreate 中轻松恢复状态。

话虽如此,官方文档对 onRestoreInstanceState 的说法如下:

Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation.

因此,为了获得最佳实践,请在 onCreate 中布置 View 层次结构,并在 onRestoreInstanceState 中恢复之前的状态。如果你这样做,任何继承你的 Activity 的人都可以选择覆盖你的 onRestoreInstanceState 来增加或替换你的恢复状态逻辑。说onRestoreInstanceState 用作模板方法,这是一个很长的路要走。

is onRestoreInstanceState called when the activity is destroyed? what does this mean?

这在 1 中得到了部分回答。是的,当系统即将销毁您的 Activity 时,会调用 onRestore。当系统处于内存压力或用户明确关闭应用程序(例如从导航栏中的最近浏览器中滑动删除)或存在配置更改(例如从陆地空间到纵向)时,系统将销毁您的 Activity 。

为什么 android 是这样设计的(不像桌面应用)?因为在移动系统上,资源管理是电池生命周期的一个严重问题。因此,您希望在应用程序生命周期中提供 Hook ,以便应用程序可以在关闭或失去焦点之间干净地保存和恢复其状态,同时使其对用户完全透明。

onRestoreInstanceState appears to be called only from instrumentation in jelly bean. Is this no longer relevant to activity lifecycle?

我不明白这个问题。能改一下吗?

关于android - onCreate 和 onRestoreInstanceState 是互斥的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12683779/

相关文章:

javascript - 当应用程序关闭时 React Native 运行任务

android - 无法使用cmd构建android项目

android - 将 developerPayload 插入到 getBuyIntent() 方法

android - 如何使用 Gradle 构建系统让 PhoneGap 项目在 Android Studio 中运行

c# - Android 上的 Unity .SVG 到 .PNG 转换

java - 从通知获取 url 并加载到 Fragment 的 webview 中的最佳方法?

android - 从sqlite数据库Android获取最后插入的值

android - 实现进度对话框

android - 我如何使用领域知识来改进这个算法?呃,重量

android - 嵌套 fragment 和后栈