简体   繁体   English

恢复时强制重新创建活动/片段

[英]Force recreation of Activity/Fragment on restore

I am having a number of issues around saving app state to a Bundle via onSaveInstanceState(). 我通过onSaveInstanceState()将应用程序状态保存到Bundle时遇到许多问题。

For now, I need to address the issue of my app crashing when it restored after being closed by Android. 现在,我需要解决我的应用在被Android关闭后恢复后崩溃的问题。

When an Activity/Fragment (in background) is being force closed by Android to regain resources, is there a way I can say "don't try and restore state when resume, just create everything anew"? 当Android强制关闭“活动/片段”(在后台)以重新获得资源时,我是否可以说“不要在恢复时尝试恢复状态,而要重新创建所有内容”?

Thanks 谢谢

In the "onCreate" method f the activity, you can pass a null value to the super call 在活动的“ onCreate”方法中,可以将空值传递给超级调用

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(null);
    //rest of your code
}

I recommend to you save your data in onPause() method. 我建议您将数据保存在onPause()方法中。 Whe you close app with HOME button onSaveInstanceState never have been called and data will be lost. WHE你关闭App HOME按钮onSaveInstanceState永远不会被调用,数据都将丢失。

is there a way I can say "don't try and restore state when resume, just create everything anew"? 有没有办法说“恢复时不要尝试恢复状态,只需重新创建所有内容”?

Yes. 是。 You can. 您可以。 You can check window state of app and manipulate your logic with boolean flags. 您可以检查应用程序的窗口状态,并使用布尔标志来操纵逻辑。 Also i will recommend to you slice save\\restore data process into 2 separate ways : 我也建议您将保存\\还原数据过程分为两种不同的方式:

  • Prepare Data to save \\ restore 准备数据以保存\\还原
  • Save \\ Restore 保存\\还原

For activity if you want to create it from scratch then just override onSaveInstanceState and call super.onSaveinstanceState passing a null al the Bundle. 对于活动,如果您想从头开始创建活动,则只需重写onSaveInstanceState并调用super.onSaveinstanceState并传递null即可。

For Fragment just set setRetainInstanceState to false in onActivityCreated method of the Fragment. 对于Fragment,只需在Fragment的onActivityCreated方法中将setRetainInstanceState设置为false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM