onSaveInstanceState()

onSaveInstanceState() is called by Android if the Activity is being stopped and may be killed before it is resumed! This means it should store any state necessary to re-initialize to the same condition when the Activity is restarted. It is the counterpart to theonCreate() method, and in fact the savedInstanceState Bundle passed in to onCreate() is the same Bundle that you construct asoutState in the onSaveInstanceState() method.

onPause() and onResume() are also complimentary methods. onPause() is always called when the Activity ends, even if we instigated that (with a finish() call for example). We will use this to save the current note back to the database. Good practice is to release any resources that can be released during an onPause() as well, to take up less resources when in the passive state.onResume() will call our populateFields() method to read the note out of the database again and populate the fields.

 

    1. onSaveInstanceState():
          @Override
         
      protectedvoid onSaveInstanceState(Bundle outState){
             
      super.onSaveInstanceState(outState);
              saveState
      ();
              outState
      .putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
         
      }

      We'll define saveState() next.

    2. onPause():
          @Override
         
      protectedvoid onPause(){
             
      super.onPause();
              saveState
      ();
         
      }
    3. onResume():
          @Override
         
      protectedvoid onResume(){
             
      super.onResume();
              populateFields
      ();
         
      }
    4. 其onSaveInstanceState方法会在什么时候被执行,有这么几种情况:


1、当用户按下HOME键时。

这是显而易见的,系统不知道你按下HOME后要运行多少其他的程序,自然也不知道activity A是否会被销毁,故系统会调用onSaveInstanceState,让用户有机会保存某些非永久性的数据。以下几种情况的分析都遵循该原则


2、长按HOME键,选择运行其他的程序时。


3、按下电源按键(关闭屏幕显示)时。


4、从activity A中启动一个新的activity时。


5、屏幕方向切换时,例如从竖屏切换到横屏时。

在屏幕切换之前,系统会销毁activity A,在屏幕切换之后系统又会自动地创建activity A,所以onSaveInstanceState一定会被执行

 

总而言之,onSaveInstanceState的调用遵循一个重要原则,即当系统“未经你许可”时销毁了你的activity,则onSaveInstanceState会被系统调用,这是系统的责任,因为它必须要提供一个机会让你保存你的数据(当然你不保存那就随便你了)。

 


至于onRestoreInstanceState方法,需要注意的是,onSaveInstanceState方法和onRestoreInstanceState方法“不一定”是成对的被调用的,onRestoreInstanceState被调用的前提是,activity A“确实”被系统销毁了,而如果仅仅是停留在有这种可能性的情况下,则该方法不会被调用,例如,当正在显示activity A的时候,用户按下HOME键回到主界面,然后用户紧接着又返回到activity A,这种情况下activity A一般不会因为内存的原因被系统销毁,故activity A的onRestoreInstanceState方法不会被执行

你可能感兴趣的:(onSaveInstanceState())