在 onCreate(Bundle savedInstanceState) 中创建的 Bundle 对象在哪里

Where is Bundle object created in onCreate(Bundle savedInstanceState)

在Android中,onCreate方法将savedInstanceState作为Bundle对象的引用。 我只想知道 Bundle 对象是在哪里以及如何创建的?

如果您将应用程序的状态保存在一个包中(通常是 onSaveInstanceState 中的非持久性动态数据),如果 activity 需要重新创建(例如,方向),它可以传回 onCreate更改),这样您就不会丢失这些先验信息。如果未提供数据,则 savedInstanceState 为空。

您需要覆盖 onSaveInstanceState(Bundle savedInstanceState) 并将要更改的应用程序状态值写入 Bundle 参数,如下所示:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putBoolean("MyBoolean", true);
  savedInstanceState.putDouble("myDouble", 1.9);
  savedInstanceState.putInt("MyInt", 1);
  savedInstanceState.putString("MyString", "Welcome back to Android");
  // etc.
}

Bundle 本质上是一种存储 NVP ("Name-Value Pair") 映射的方法,它将传递给 onCreate() 和 onRestoreInstanceState(),您可以在其中提取值,如下所示:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
  double myDouble = savedInstanceState.getDouble("myDouble");
  int myInt = savedInstanceState.getInt("MyInt");
  String myString = savedInstanceState.getString("MyString");
}