0

它是关于 void onSaveInstanceState(Bundle saved) 和一个基本的 java 概念。

在调用此方法之前必须创建一个 Bundle 对象,然后将其传递给此方法。假设它是这样创建和传递的:

Bundle savedInstanceState= new Bundle();
onSaveInstanceState(savedInstanceState);

此方法将数据保存在该捆绑包中。但它不会返回那个包(它已经添加了名称-值对)。

public void onSaveInstanceState(Bundle saved){
. . . //data added to the bundle named saved
} 

因此,被声明为参数变量的已保存包仅在方法中具有范围。在方法内部添加到 save 的数据不会添加到 savedInstanceState。该方法也没有返回任何东西。

那么,当它不更改自身外部的任何包并且也不返回任何内容时,此方法的意义是什么?

我们还说传递给 onCreate 的包携带了之前保存的活动冻结状态。似乎这个包来自 onSavedInstanceState() 中的处理,但该方法不返回任何内容,也不会更改传递给它的包的值,在它自身之外。我很困惑。

如果有人可以帮助我理解这个概念,我将不胜感激。是的,我已阅读 Activity API 中给出的参考。

4

2 回答 2

1

So, lets say you override onSaveInstanceState method in your custom activiy, something like this :

public void onSaveInstanceState(Bundle dataToBeSaved) {
    super.onSaveInstanceState(dataToBeSaved);
    dataToBeSaved.putString("myKey", "myImportantStringValue"); 
    //populate bundle with more data
} 

Here is what happens (simplified) when your activity is being killed and has a chance to save some data :

  • Android system will create Bundle data = new Bundle(); as you correctly stated in your question.
  • Android will call your activity.onSaveInstanceState(data); passing reference to just created Bundle object.
  • your onSaveInstance method receives copy of that reference (named as dataToBeSaved inside your method). Note that this reference(and its copy) refer to the Bundle object managed by system. Your method will therefore populate this system-managed Bundle object.
  • System keeps modified Bundle object while your activity is being restarted
  • When your activity is back, system will call your activity.onCreate(data); passing [reference to] this previously stored Bundle
  • In your onCreate() you get a reference to a Bundle object with the same content as one you accessed in onSaveInstanceState()
    [comment-based edit] You will get reference to exactly same Bundle or its re-created duplicate depending on how system manages memory between activity/process restart and this is irrelevant for developer.

Hope that clarifies things for you.

于 2013-11-05T20:21:08.543 回答
1

根据您的问题:

那么,当它不更改自身外部的任何包并且也不返回任何内容时,此方法的意义是什么?

我认为你完全错过了方法本身的全部意义,甚至超出了参数,让你有机会在重新创建后收集一些你可能感兴趣的信息,这种方法的重点是让你知道一种机制可能会使对象失去它的状态即将开始。例如,您可以注意到该方法在您的设备旋转时执行,并且活动的“重新创建”将影响对象的当前状态,让您有机会保存信息并在“onRestoreInstanceState”中使用它,你也可能注意到,如果你按下并关闭一个活动,它不会被执行,因为你不再关心这些对象的状态,所以除了你在包中得到的任何东西(这是你填充的责任),

希望这能澄清你的问题......

问候!

于 2013-11-05T20:13:02.497 回答