简体   繁体   English

Android会阻止恢复活动

[英]Android prevent restoring the activity

I have a viewpager holding many fragments. 我有一个viewpager持有许多片段。 When the activity is sent to background and when resources are needed, the OS will kill the app or at least some fragments. 当活动发送到后台并且需要资源时,操作系统将终止应用程序或至少一些片段。 When I return to the activity it crashes because the activity tries to attach new instances of all fragments it held before the clean-up and now some fields are null. 当我返回活动时它会崩溃,因为活动会尝试在清理之前附加它所拥有的所有片段的新实例,现在某些字段为空。 This of course could be fixed by properly implementing state saving and restoring using Bundles, but I don't want to do that. 这当然可以通过使用Bundle正确实现状态保存和恢复来修复,但我不想这样做。 Instead I want to prevent restoring the fragments. 相反,我想阻止恢复碎片。 Is there a way to tell the OS that once it has sent the GC in and destroyed fragments, it shouldn't bother recreating them at all? 有没有办法告诉操作系统,一旦它发送了GC并销毁了碎片,它根本不应该重新创建它们? Once the cleaning-up happens, I want the activity to be simply recreated on return, as if a user launched it by taping the icon. 一旦清理完成,我希望在返回时简单地重新创建活动,就像用户通过点击图标启动它一样。 Any chance of doing that? 有机会这样做吗?

The proposed solution here https://stackoverflow.com/a/15683289/552735 does not work. 建议的解决方案https://stackoverflow.com/a/15683289/552735不起作用。 It causes exceptions java.lang.IllegalStateException: Fragement no longer exists for key f2: index 3 它会导致异常java.lang.IllegalStateException:键f2:index 3不再存在Fragement

I had a problem just like this. 我有这样的问题。 Here's how I fixed it: 以下是我修复它的方法:

    @Override 
    protected void onSaveInstanceState(Bundle savedInstanceState)
    {
        savedInstanceState.clear();
    }

Note that this method will ensure that absolutely no UI state information will be stored when the Activity is killed by the system - this has the effect of also not restoring any Views when onRestoreInstanceState() gets called with the same Bundle after onStart() . 请注意,此方法将确保在系统onRestoreInstanceState() Activity时绝对不会存储UI状态信息 - 当onStart()之后使用相同的Bundle调用onRestoreInstanceState()时,这onRestoreInstanceState()无法恢复任何视图。

You can't disable the save/restore instance state actions. 您无法禁用保存/恢复实例状态操作。 In case you don't want to actually implement this logic, you have to reload the form especially if your form heavily loaded with fragments. 如果您不想实际实现此逻辑,则必须重新加载表单,尤其是在表单重载片段时。

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
     startActivity(new Intent(this,YOUR_ACTIVITY.class));
     finish();
}

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

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