一、方法调用时间
- onSaveInstanceState是用来保存UI状态,在Activity杀死之前,它一般在onStop或者onPause之前触发;
- onRestoreInstanceState是在onResume之前触发来恢复状态;
- Activity被杀死了,onCreate会被调用,且onRestoreInstanceState在 onResume之前恢复上次保存的信息;
- Activity没被杀死,onCreate不会被调用,但onRestoreInstanceState 仍然会被调用,在 onResume之前恢复上次保存的信息;
二、方法使用场景
- onSaveInstanceState() 只有在Acitivity被系统kill掉时才会调用。所以通常onSaveInstanceState()只适合用于保存一些临时性的状态,而onPause()适合用于数据的持久化保存。
- onSaveInstanceState()方法只适合保存瞬态数据, 比如UI控件的状态, 成员变量的值等,而不应该用来保存持久化数据,持久化数据应该当用户离开当前的activity时,在onPause()中保存(比如将数据保存到数据库或文件中)。说到这里,还要说一点的就是在onPause()中不适合用来保存比较费时的数据,所以这点要理解。
- 由于onSaveInstanceState()方法方法不一定会被调用, 因此不适合在该方法中保存持久化数据, 例如向数据库中插入记录等. 保存持久化数据的操作应该放在onPause()中。若是永久性值,则在onPause()中保存;若大量,则另开线程吧,别阻塞UI线程。
三、使用方法
1.在onSaveInstanceState方法中保存bundle:
@Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mMapView.onSaveInstanceState(outState); saveState(outState); } @Override protected void onRestoreInstanceState(Bundle InState) { super.onRestoreInstanceState(InState); mMapView.onSaveInstanceState(InState); restoreState(InState); }
/** * 进入三维模块后,该activity会被kill掉,此处保存被杀掉前的一些状态数据 * * @param outState */ private void saveState(Bundle outState) { outState.putParcelable(HBContant.KEY_STATE_ESTATEINFO_JSON, mJson); outState.putParcelable(HBContant.KEY_STATE_ESTATEINFO_GALLERY, mGalleryJson); outState.putParcelable(HBContant.KEY_STATE_ESTATEINFO_FLASH, mFlashJson); outState.putParcelableArrayList(HBContant.KEY_STATE_ESTATEINFO_VIDEO, mVideoList); outState.putParcelableArrayList(HBContant.KEY_STATE_ESTATEINFO_NEWS, mNewsList); outState.putParcelableArrayList(HBContant.KEY_STATE_ESTATEINFO_HOUSELIST, mEstateHouseList); } private void restoreState(Bundle inState) { }
2.在oncreate或者onRestoreInstanceState方法中读取保存的bundle:
if (savedInstanceState == null) { //正常情况 loadTask(); } else { //进入三维图被kill后返回,恢复页面数据 mJson = savedInstanceState.getParcelable(HBContant.KEY_STATE_ESTATEINFO_JSON); mGalleryJson = savedInstanceState.getParcelable(HBContant.KEY_STATE_ESTATEINFO_GALLERY); mFlashJson = savedInstanceState.getParcelable(HBContant.KEY_STATE_ESTATEINFO_FLASH); mVideoList = savedInstanceState.getParcelableArrayList(HBContant.KEY_STATE_ESTATEINFO_VIDEO); mNewsList = savedInstanceState.getParcelableArrayList(HBContant.KEY_STATE_ESTATEINFO_NEWS); mEstateHouseList = savedInstanceState.getParcelableArrayList(HBContant.KEY_STATE_ESTATEINFO_HOUSELIST); if(mJson != null && mGalleryJson != null && mFlashJson != null && mVideoList != null && mEstateHouseList != null) { loadComplete(); } else { loadTask(); } }
Android笔记:onSaveInstanceState和onRestoreInstanceState总结
时间: 2024-10-24 07:50:56