【问题标题】:Is there any need to use onSaveInstanceState and onRestoreInstanceState when using Android Architecture Components LiveData & ViewModel?使用 Android 架构组件 LiveData & ViewModel 时是否需要使用 onSaveInstanceState 和 onRestoreInstanceState?
【发布时间】:2017-06-15 07:32:08
【问题描述】:

Android Architecture Components 提供了LiveDataViewModel 类,它们对生命周期更友好,专为更精简的活动/片段而设计。这些类处理跨配置更改的数据存储,但与 Activity 框架 API 相比,我对它们的使用感到困惑。 onSaveInstanceState(Bundle)onRestoreInstanceState(Bundle) 对于保持活动状态是否仍然必要或有用?

【问题讨论】:

    标签: android viewmodel android-livedata android-architecture-components


    【解决方案1】:

    onSaveInstanceState & onRestoreInstanceState 还是有用的。

    ViewModel 仅在进程处于活动状态时保存数据。
    但是,onSaveInstanceState 和 onRestoreInstanceState 可以在进程被杀死的情况下保存数据。

    ViewModel 易于使用,可用于在屏幕方向更改时保留大数据。
    onSaveInstanceState & onRestoreInstanceState 可以在进程处于后台时保存数据。(在后台,应用进程可以随时被系统杀死。)

    【讨论】:

      【解决方案2】:

      假设一个场景: 用户在 activity A 中,然后导航到 activity B

      但由于内存不足,Android OS 会破坏 activity A ,因此与之相连的 ViewModel 也会破坏。 (您可以通过在开发者选项中检查Don't keep activities 来模拟它)

      现在用户导航回activity A,Android 操作系统尝试创建新的AcivityViewModel 对象。因此,您在ViewModel 中丢失了数据。

      但 savedInstanceState 中的值仍然存在。

      【讨论】:

        猜你喜欢
        • 2011-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-16
        • 2018-02-28
        • 1970-01-01
        • 1970-01-01
        • 2018-10-21
        相关资源
        最近更新 更多