当切换到其它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应用中通过将单例模式变量定义为全局变量或在onSaveInstanceState中进行保存,来避免内存不足时变量被回收导致的数据丢失问题。通过实例代码演示了实现过程。
2885

被折叠的 条评论
为什么被折叠?



