android基础之onSaveInstanceState用法(一)保存容易被回收的自定义类的静态全局变量

当切换到其它apk时且内存不足时,在之前设置的单例模式静态变量会被回收掉。解决方法要么定义为Applicantion全局变量,要么在onSaveInstanceState中保存


@Override

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//恢复容易被回收的投保人

if(savedInstanceState!=null){

//自定义单例

InsuranceFormAgent insFormAgent = InsuranceFormAgent.createInstance();
CustomerDetailInfo applicant = (CustomerDetailInfo) savedInstanceState.getSerializable("Applicant");
if(applicant!=null){
insFormAgent.setApplicantInfo(applicant);
}
AppLog.debug("-------ActProposalChooseProduct---------onCreate get the savedInstanceState---------");
}

setContentView(R.layout.demo_pro_choose_insurant);

}



@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// 为了防止万一程序被销毁的风险,这个方法可以保证重要数据的正确性
// 不写这个方法并不意味着一定出错,但是一旦遇到了一些非常奇怪的数据问题的时候
// 可以看看是不是由于某些重要的数据没有保存,在程序被销毁时被重置
// Save away the original text, so we still have it if the activity needs to be killed while paused.


//切换到其它apk时,当内存不足时,在之前设置的静态变量投保人会被回收掉。所以在此要保存
InsuranceFormAgent insFormAgent = InsuranceFormAgent.createInstance();
CustomerDetailInfo customer = insFormAgent.getmApplicantInfo();
savedInstanceState.putSerializable(APPLICANT,customer);
super.onSaveInstanceState(savedInstanceState);
AppLog.debug("-----------ActDemoProChooseInsurant---------------onSaveInstanceState--");
}


@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// int mCount = savedInstanceState.getInt("IntTest");
//恢复容易被回收的投保人
if(savedInstanceState!=null){
InsuranceFormAgent insFormAgent = InsuranceFormAgent.createInstance();
CustomerDetailInfo applicant = (CustomerDetailInfo) savedInstanceState.getSerializable(APPLICANT);
if(applicant!=null){
insFormAgent.setApplicantInfo(applicant);
}
}
AppLog.debug("------ActDemoProChooseInsurant----------onRestoreInstanceState---");
}

你可能感兴趣的:(android)