由于系统Android 的GC回收机制以及进程处理机制会导致后台页面资源被回收或者一些系统操作导致页面被回收.这个时候我们就需要在切换到当前App的时候恢复原先的页面
思路:
- onSaveInstanceState(outState: Bundle) 方法保存 页面数据.
- 在onCreate(savedInstanceState: Bundle?) 方法中 获取保存的数据重新加载数据
方法介绍:
- 保存数据: Activity中实现,onSaveInstanceState(outState: Bundle) ,在终止活动之前调用此方法,以便在将来的某个时间返回时,它可以恢复其状态
Called to retrieve per-instance state from an activity before being killed
//调用以在终止活动之前从活动中检索每个实例的状态
This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored
//此方法在活动可能被终止之前调用,以便在将来某个时间它返回时可以恢复其状态。例如,如果活动B在活动A之前启动,并且在某个时间点活动A被终止以回收资源,则活动A将有机会通过此方法保存其用户界面的当前状态,以便当用户返回到活动A时,可以恢复用户界面的状态
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (outState != null) {
if (!TextUtils.isEmpty(mAddressId)) {
outState.putString("mAddressId", mAddressId)
}
outState.putString(RouterConstant.Shop.PARAM_GOODS_TYPE, goodsType)
outState.putString(RouterConstant.Shop.PARAM_GOODS_ID, goodsId)
outState.putString(RouterConstant.Shop.PARAM_UID, UserUtils.getUserId() )
}
}

2: 恢复数据,onCreate(savedInstanceState: Bundle?)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//savedInstanceState 数据保存后的对象
if (savedInstanceState != null) {
mAddressId = savedInstanceState.getString("mAddressId") ?: "0"
goodsType = savedInstanceState.getString(RouterConstant.Shop.PARAM_GOODS_TYPE) ?: "1"
goodsId = savedInstanceState.getString(RouterConstant.Shop.PARAM_GOODS_ID) ?: ""
uId = savedInstanceState.getString(RouterConstant.Shop.PARAM_UID) ?: ""
} else {
goodsId = intent.getStringExtra(RouterConstant.Shop.PARAM_GOODS_ID)
if (intent.getStringExtra(RouterConstant.Shop.PARAM_GOODS_TYPE) == null) {
goodsType = "1"
} else {
goodsType = intent.getStringExtra(RouterConstant.Shop.PARAM_GOODS_TYPE) ?: "1"
}
}
}



总结:
数据恢复是处理异常情况导致页面销毁 必不可少的一部分.所以想降低页面崩溃次数和兼容各种复杂情况 建议给页面做一些页面恢复的逻辑
网友评论