java - 尚存的配置更改机制如何工作?

标签 java android kotlin android-fragments android-activity

关于尚存的配置更改,我有三个类似的问题。我知道在配置更改中保留对象的三种方法,但是我不知道它们在后台如何工作。

  • 覆盖onSaveInstanceState。我知道它将数据放入 bundle 包中。但是它如何在配置更改中生存下来?真正的 bundle 包是什么?它属于 Activity 吗?我们的应用程序中只有一个 bundle 包吗? (我知道我们可以创建不同的实例,但是当我们使用putExtraonSaveInstanceState或任何其他方法放置数据时,它们会到达同一位置吗?)
  • 使用onRetainNonConfigurationInstance()getLastNonConfigurationInstance()。这用于在配置更改时保留viewModelStore。那么它是如何工作的以及将数据放在何处?(我知道有关剥夺)
  • Retained(Holder)片段和片段中的setRatinInstance()方法。相同的问题(我认为 Activity 为此仅使用onRetainNonConfigurationInstance(),如果我错了,请纠正我)

  • 我在网上和StackOverflow上搜索了此内容,但找不到任何内容。我也尝试过实际的代码,但是没有运气!
    由于这些问题是相关的,我想我将它们全部放在一个问题中。希望一切都好。

    最佳答案

    Overriding onSaveInstanceState. I know it puts the data in the bundle. but how does it survive configuration changes? what really bundle is? does it belong to activity? do we have only one bundle in the app? (I know we can make different instances but when we put our data with putExtra or onSaveInstanceState or any other method, are they going to the same place?)


    这并不是真正的“在配置更改中保留”,而是“在过程级持久性上节省”,然后将其重新用于配置更改。之所以我不将其视为“保留”,是因为该对象被包裹为“可包裹”,然后在恢复时创建了副本。
    无论如何,the ActivityRecord has a bundle,每个任务堆栈都有其自己的ActivityRecords,并且当发生进程死亡时,系统会保存和还原任务堆栈。这种机制恰好发生在“还可以处理配置更改”。Intent.putExtra的工作原理非常相似,是的。

    Using onRetainNonConfigurationInstance() and getLastNonConfigurationInstance(). this is used to retain viewModelStore across configuration changes. so how it works and where does it put the data?(I know about deprication)


    onSaveInstanceState不同,这实际上是操作系统级别的回调,仅用于在配置更改时保留对象。过去曾经是onRetainCustomNonConfigurationInstance / getLastCustomNonConfigurationInstance,但是由于ViewModel旨在成为在配置更改中保留的“唯一标准”方式,因此不赞成使用ViewModel。在内部,它只是onRetainNonConfigurationInstance(是 map )的viewModelStore

    Retained(Holder) Fragment and setRetainInstance() method in the fragment. the same question(I think the activity just uses the onRetainNonConfigurationInstance() for this, correct me if I'm wrong)


    是的,尽管不幸的是,最新的Jetpack Fragments版本也弃用了此功能(以简化片段及其生命周期的交互)。片段管理器作为非配置保留,保留的片段使用onRetainNonConfigurationInstance()FragmentActivity与它一起保留(我认为现在称为FragmentManagerViewModel)。
    非配置实例保存在the ActivityClientRecord中,但ActivityStack不会保留这些实例。
    希望覆盖足够。

    关于java - 尚存的配置更改机制如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64253762/

    相关文章:

    java - 如何在 scala 中使用函数式编程过滤列表?

    android - 从 SherlockActionBar fragment 选项卡动态添加菜单项

    javascript - Windows 中的 "~/.gradle"文件夹在哪里?

    Observable<T>.subscribe 上的 Kotlin 扩展函数不起作用

    java扩展静态方法,无法编译,为什么?

    java - 为什么我会从另一个(Java)调用构造函数?

    java - 从终端运行使用 Maven 编译的主类

    android - 自动滚动回收 View slider

    reflection - Kotlin:如何访问委托(delegate)的 get- 和 setValue 方法?

    android - 使用 Jenkins 构建 APK 时出现 kotlin.KotlinNullPointerException(无错误消息)