在哪里可以使用 onSaveInstanceState 参数传递不同 Activity?

Where can be use onSaveInstanceState where parameters are passed different Activity?

对于 Acitivity 已经有一个名为 onSaveInstacestate(Bundle) 的方法,它用于存储 activity 的数据,这是被覆盖的方法。

据我所知,有两个不同的 onSaveInstanceState,其中参数的传递方式不同,如下所示。

@Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState)
    {
        super.onSaveInstanceState(outState, outPersistentState);
        Log.i("test", "onSaveInstanceState called **********");
    }

@Override
    protected void onSaveInstanceState(Bundle outState)
    {
         super.onSaveInstanceState(outState);
          Log.i("test", "onSaveInstanceState with bundle only called");
    }

那么,这两种方法在什么情况下可以使用呢? 请详细描述。 提前致谢。

从 API 级别 21 开始,onSaveInstanceState() 有一个名为 PersistableBundle 的对象的新参数。您可以在 Docs

上阅读有关 PersistableBundle 的更多信息

简而言之,

API 21 岁及以上

@Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState)
    {
        super.onSaveInstanceState(outState, outPersistentState);
        Log.i("test", "onSaveInstanceState called **********");
    }

对于 API 小于 20

@Override
    protected void onSaveInstanceState(Bundle outState)
    {
         super.onSaveInstanceState(outState);
          Log.i("test", "onSaveInstanceState with bundle only called");
    }

这值得一个扩展的答案。正如已接受的答案所述,自 API 级别 21 以来,onSaveInstanteState.

有一个额外的过载

从 API 级别 1 (Docs) 开始可用:

void onSaveInstanceState (Bundle outState)

在 API 级别 21 (Docs) 中引入的添加:

void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState)

带有 PersistableBundle 的后一个不是前一个的替代品。它仅在 Activity 属性 R.attr.persistableMode 设置为 persistAcrossReboots 时使用。当要持久化这样的 Activity 时,将调用 onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState) 并且您会收到一个 PersistableBundle 来存储您的实例状态。

要将 R.attr.persistableMode 设置为 persistAcrossRebootsActivity 的状态恢复为

void onRestoreInstanceState (Bundle savedInstanceState, PersistableBundle persistentState)

请注意,如果调用带有 PersistableBundle 的那个,则不会调用 onRestoreInstanceState (Bundle savedInstanceState)。我假设 onSaveInstanceState 也是如此,但我没有检查过,文档在 API 级别 28 时也没有提到它。

onCreate().

也有适当的重载

我只能说什么,但这是一些帮助代码可以帮助你 我在基础 activity 中执行此操作以确保始终保存我的数据

public abstract void saveInstanceState(Bundle outState, PersistableBundle outPersistentState);

@Override
public final void onSaveInstanceState(@NonNull Bundle outState, PersistableBundle outPersistentState) {
    saveInstanceState(outState, outPersistentState);
    super.onSaveInstanceState(outState, outPersistentState);
}

@Override
protected final void onSaveInstanceState(@NonNull Bundle outState) {
    saveInstanceState(outState, null);
    super.onSaveInstanceState(outState);
}

我正在使用 final 关键字,所以我不会忘记并重写其中一种方法 而不是我自定义的抽象