核心提示:先看Application Fundamentals上的一段话:Android calls onSaveInstanceState() before the activity becomes vulnerable to being destroyed by the system, but does not bother


先看Application Fundamentals上的一段话:


Android calls onSaveInstanceState() before the activity becomes vulnerable to being destroyed by the system, but does not bother calling it when the instance is actually being destroyed by a user action (such as pressing the BACK key)


从这句话可以知道,当某个activity变得“容易”被系统销毁时,该activity的onSaveInstanceState就会被执行,除非该activity是被用户主动销毁的,例如当用户按BACK键的时候。


注意上面的双引号,何为“容易”?言下之意就是该activity还没有被销毁,而仅仅是一种可能性。这种可能性有哪些?通过重写一个 activity的所有生命周期的onXXX方法,包括onSaveInstanceState和onRestoreInstanceState方法,我们可以清楚地知道当某个activity(假定为activity A)显示在当前task的最上层时,其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方法不会被执行


另外,onRestoreInstanceState的bundle参数也会传递到onCreate方法中,你也可以选择在onCreate方法中做数据还原

更多相关文章

  1. Android解析包名信息
  2. android 捕获返回(后退)按钮事件的两种方法
  3. Android4.1 Rotation 小结
  4. Android中调用设备的照相和摄像功能
  5. Android(安卓)System.gc()注意点
  6. Dealing with bitmap object in android NDK
  7. android抓取各种log的方法
  8. 浅谈Java中Collections.sort对List排序的两种方法
  9. Python list sort方法的具体使用

随机推荐

  1. Textview基本属性及功能
  2. Android数据存储
  3. android 上调试动态库方法
  4. Android关于LinearLayout的设置问题
  5. Android音频架构解析
  6. android TabHost选项卡示例
  7. Android多线程同步转异步方法总结
  8. Android Studio 2.0 Preview发布,附下载
  9. android开发每日汇总【2011-11-02】
  10. Android带播放进度条的音乐播放器