首页 文章

IllegalStateException:使用ViewPager在onSaveInstanceState之后无法执行此操作

提问于
浏览
405

我从我的应用程序中获取用户报告,提供以下异常:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1109)
at android.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:399)
at android.app.Activity.onBackPressed(Activity.java:2066)
at android.app.Activity.onKeyUp(Activity.java:2044)
at android.view.KeyEvent.dispatch(KeyEvent.java:2529)
at android.app.Activity.dispatchKeyEvent(Activity.java:2274)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1803)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1855)
at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1277)
at android.app.Activity.dispatchKeyEvent(Activity.java:2269)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1803)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.widget.TabHost.dispatchKeyEvent(TabHost.java:297)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1112)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1855)
at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1277)
at android.app.Activity.dispatchKeyEvent(Activity.java:2269)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1803)
at android.view.ViewRoot.deliverKeyEventPostIme(ViewRoot.java:2880)
at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2853)
at android.view.ViewRoot.handleMessage(ViewRoot.java:2028)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:132)
at android.app.ActivityThread.main(ActivityThread.java:4028)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:491)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)

显然它与FragmentManager有关,我不使用它 . stacktrace没有显示我自己的任何类,所以我不知道这个异常发生在哪里以及如何防止它 .

对于记录:我有一个tabhost,并且在每个选项卡中都有一个ActivityGroup在Activities之间切换 .

28 回答

  • 6

    我也遇到过这个问题,每次 FragmentActivity 的上下文发生变化时都会出现问题(例如屏幕方向改变等) . 所以最好的解决方法是从 FragmentActivity 更新上下文 .

  • 0

    如果您使用popBackStack()或popBackStackImmediate()方法崩溃,请尝试使用以下方法:

    if (!fragmentManager.isStateSaved()) {
                fragmentManager.popBackStackImmediate();
            }
    

    这对我也有用 .

  • 648

    请检查我的答案here . 基本上我只需要:

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //No call for super(). Bug on API Level > 11.
    }
    

    不要在 saveInstanceState 方法上调用 super() . 这搞砸了......

    这是支持包中已知的bug .

    如果您需要保存实例并向 outState Bundle 添加内容,则可以使用以下内容:

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE");
        super.onSaveInstanceState(outState);
    }
    

    最后,正确的解决方案(如评论中所示)使用:

    transaction.commitAllowingStateLoss();
    

    添加或执行导致 ExceptionFragmentTransaction 时 .

  • 20

    类似的错误消息存在许多相关问题 . 检查此特定堆栈跟踪的第二行 . 此异常特别与对 FragmentManagerImpl.popBackStackImmediate 的调用有关 .

    如果已保存会话状态,则此方法调用(如 popBackStack )将始终以 IllegalArgumentException 失败 . 检查来源 . 没有什么可以阻止抛出此异常 .

    • 删除对 super.onSaveInstanceState 的调用无济于事 .

    • 使用 commitAllowingStateLoss 创建片段无济于事 .

    以下是我观察问题的方法:

    • 有一个带有提交按钮的表单 .

    • 单击该按钮时,将创建一个对话框并启动异步过程 .

    • 用户在流程完成前单击主页键 - 调用 onSaveInstanceState .

    • 该过程完成,进行回调并尝试 popBackStackImmediate .

    • IllegalStateException 被抛出 .

    这是我为解决它所做的事情:

    由于无法避免回调中的 IllegalStateException ,请捕获并忽略它 .

    try {
        activity.getSupportFragmentManager().popBackStackImmediate(name);
    } catch (IllegalStateException ignored) {
        // There's no way to avoid getting this if saveInstanceState has already been called.
    }
    

    这足以阻止应用程序崩溃 . 但现在用户将恢复应用程序并看到他们认为按下的按钮根本没有被按下(他们认为) . 表单片段仍在显示!

    要解决此问题,请在创建对话框时,进行一些状态以指示进程已启动 .

    progressDialog.show(fragmentManager, TAG);
    submitPressed = true;
    

    并将此状态保存在捆绑中 .

    @Override
    public void onSaveInstanceState(Bundle outState) {
        ...
        outState.putBoolean(SUBMIT_PRESSED, submitPressed);
    }
    

    不要忘记在 onViewCreated 再次加载

    然后,在恢复时,如果先前尝试过提交,则回滚片段 . 这可以防止用户回到看似未提交的表单 .

    @Override
    public void onResume() {
        super.onResume();
        if (submitPressed) {
            // no need to try-catch this, because we are not in a callback
            activity.getSupportFragmentManager().popBackStackImmediate(name);
            submitPressed = false;
        }
    }
    
  • 0

    在显示片段之前检查活动 isFinishing() 并注意 commitAllowingStateLoss() .

    例:

    if(!isFinishing()) {
    FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                DummyFragment dummyFragment = DummyFragment.newInstance();
                ft.add(R.id.dummy_fragment_layout, dummyFragment);
                ft.commitAllowingStateLoss();
    }
    
  • 0

    以下是此问题的不同解决方案 .

    使用私有成员变量,您可以将返回的数据设置为intent,然后可以在super.onResume()之后处理;

    像这样:

    private Intent mOnActivityResultIntent = null; 
    
    @Override
    protected void onResume() {
        super.onResume();
        if(mOnActivityResultIntent != null){
            ... do things ...
            mOnActivityResultIntent = null;
        }
     }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        if(data != null){
            mOnActivityResultIntent = data;
        }
    }
    
  • 0

    这是2017年10月,谷歌使用新的东西调用生命周期组件制作Android支持库 . 它为此问题提供了一些新的想法'在onSaveInstanceState之后无法执行此操作'问题 .

    In short:

    • 使用生命周期组件确定弹出片段的正确时间 .

    Longer version with explain:

    • 为什么会出现这个问题?

    这是因为你试图从你的活动中使用 FragmentManager (我想要保留你的片段?)为你的片段提交一个事务 . 通常这看起来就像你正在尝试为即将到来的片段做一些事务,同时主机活动已经调用了 savedInstanceState 方法(用户可能碰巧触摸了主页按钮,因此活动调用 onStop() ,在我的情况下,这是原因)

    通常这个问题不应该发生 - 我们总是尝试在最开始时将片段加载到活动中,就像 onCreate() 方法是一个完美的地方 . 但有时这个 do happen ,特别是当你无法决定你将加载到该活动的片段,或者你正在尝试从 AsyncTask 块加载片段(或者任何事情需要一点时间) . 在片段事务真正发生之前的时间,但在活动的 onCreate() 方法之后,用户可以做任何事情 . 如果用户按下主页按钮,触发活动的 onSavedInstanceState() 方法,则会出现 can not perform this action 崩溃 .

    如果有人想在这个问题上看得更深,我建议他们看一下这个博客post . 它看起来深入内部代码层并解释了很多 . 此外,它给出了您不应该使用 commitAllowingStateLoss() 方法来解决此崩溃的原因(相信我,它对您的代码没有任何好处)

    • 如何解决这个问题?

    • 我应该使用 commitAllowingStateLoss() 方法加载片段吗? Nope you shouldn't ;

    • 我应该覆盖 onSaveInstanceState 方法,忽略里面的 super 方法吗? Nope you shouldn't ;

    • 我应该使用神奇的 isFinishing inside活动来检查主机活动是否适合片段交易?是啊 looks like 正确的方法 .

    • 看看Lifecycle组件可以做什么 .

    基本上,Google在 AppCompatActivity 类(以及您应该在项目中使用的其他几个基类)中进行了一些实现,这使得它更容易 determine current lifecycle state . 回顾一下我们的问题:为什么会出现这个问题?这是因为我们在错误的时间做某事 . 所以我们尽量不这样做,这个问题就会消失 .

    我为自己的项目编写了一些代码,这是我使用 LifeCycle 做的 . 我在Kotlin编码 .

    val hostActivity: AppCompatActivity? = null // the activity to host fragments. It's value should be properly initialized.
    
    fun dispatchFragment(frag: Fragment) {
        hostActivity?.let {
           if(it.lifecyclecurrentState.isAtLeast(Lifecycle.State.RESUMED)){
               showFragment(frag)
           }
        }
    }
    
    private fun showFragment(frag: Fragment) {
        hostActivity?.let {
            Transaction.begin(it, R.id.frag_container)
                    .show(frag)
                    .commit()
        }
    

    正如我在上面所示 . 我将检查主机活动的生命周期状态 . 借助支持库中的Lifecycle组件,这可能更具体 . 代码 lifecyclecurrentState.isAtLeast(Lifecycle.State.RESUMED) 表示,如果当前状态至少是 onResume ,不迟于它?这确保我的方法不会在其他生命状态期间执行(如 onStop ) .

    • 这一切都完成了吗?

    当然不是 . 我展示的代码告诉了一些防止应用程序崩溃的新方法 . 但是如果它确实进入了 onStop 的状态,那行代码就不会做任何事情,因此屏幕上不会显示任何内容 . 当用户回到应用程序时,他们会看到一个空屏幕,这是一个不好的经历(是的,比崩溃好一点) .

    所以在这里我希望有更好的东西:如果生命状态晚于 onResume ,应用程序不会崩溃,事务方法是生命状态感知;此外,在用户回到我们的应用程序之后,活动将尝试继续完成该片段事务操作 .

    我在这个方法中添加了更多内容:

    class FragmentDispatcher(_host: FragmentActivity) : LifecycleObserver {
        private val hostActivity: FragmentActivity? = _host
        private val lifeCycle: Lifecycle? = _host.lifecycle
        private val profilePendingList = mutableListOf<BaseFragment>()
    
        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        fun resume() {
            if (profilePendingList.isNotEmpty()) {
                showFragment(profilePendingList.last())
            }
        }
    
        fun dispatcherFragment(frag: BaseFragment) {
            if (lifeCycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) == true) {
                showFragment(frag)
            } else {
                profilePendingList.clear()
                profilePendingList.add(frag)
            }
        }
    
        private fun showFragment(frag: BaseFragment) {
            hostActivity?.let {
                Transaction.begin(it, R.id.frag_container)
                        .show(frag)
                        .commit()
            }
        }
    }
    

    我在这个 dispatcher 类中维护一个列表,以存储那些没有机会完成事务操作的片段 . 当用户从主屏幕返回并发现仍有片段等待启动时,它将转到 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) 注释下的 resume() 方法 . 现在我认为它应该像我预期的那样工作 .

  • 0

    Short And working Solution :

    遵循简单步骤

    脚步

    步骤1:在相应的片段中覆盖 onSaveInstanceState 状态 . 并从中删除超级方法 .

    @Override
    public void onSaveInstanceState( Bundle outState ) {
    
    }
    

    第2步:使用 fragmentTransaction.commitAllowingStateLoss( );

    片段操作时代替 fragmentTransaction.commit( ); .

  • 48

    BEWARE ,使用 transaction.commitAllowingStateLoss() 可能会导致用户体验不佳 . 有关抛出此异常的原因的详细信息,请参阅this post .

  • 15

    我找到了解决这类问题的肮脏方案 . 如果你仍然想出于任何原因保留你的 ActivityGroups (我有时间限制的原因),你只需要实现

    public void onBackPressed() {}
    

    在你的 Activity 并在那里做一些 back 代码 . 即使旧设备上没有这样的方法,这个方法也会被更新的方法调用 .

  • 0

    不要使用commitAllowingStateLoss(),它只应用于UI状态可以在用户上意外更改的情况 .

    https://developer.android.com/reference/android/app/FragmentTransaction.html#commitAllowingStateLoss()

    如果事务发生在parentFragment的ChildFragmentManager中,请使用 parentFragment.isResume() outside来检查 .

    if (parentFragment.isResume()) {
        DummyFragment dummyFragment = DummyFragment.newInstance();
        transaction = childFragmentManager.BeginTransaction();
        trans.Replace(Resource.Id.fragmentContainer, startFragment);
    }
    
  • 1

    我有类似的问题,场景是这样的:

    • 我的活动是添加/替换列表片段 .

    • 每个列表片段都有对活动的引用,以便在单击列表项时通知活动(观察者模式) .

    • 每个列表片段在其 onCreate 方法中调用 setRetainInstance(true); .

    activityonCreate 方法是这样的:

    mMainFragment = (SelectionFragment) getSupportFragmentManager()
                    .findFragmentByTag(MAIN_FRAGMENT_TAG);
            if (mMainFragment == null) {
                mMainFragment = new SelectionFragment();
    
                mMainFragment.setListAdapter(new ArrayAdapter<String>(this,
                        R.layout.item_main_menu, getResources().getStringArray(
                                R.array.main_menu)));
    mMainFragment.setOnSelectionChangedListener(this);
                FragmentTransaction transaction = getSupportFragmentManager()
                        .beginTransaction();
                transaction.add(R.id.content, mMainFragment, MAIN_FRAGMENT_TAG);
                transaction.commit();
            }
    

    抛出异常是因为when配置更改(设备已旋转),活动已创建,主片段从片段管理器的历史记录中检索,同时片段已经 OLD 引用了 destroyed activity

    将实现更改为此解决了问题:

    mMainFragment = (SelectionFragment) getSupportFragmentManager()
                    .findFragmentByTag(MAIN_FRAGMENT_TAG);
            if (mMainFragment == null) {
                mMainFragment = new SelectionFragment();
    
                mMainFragment.setListAdapter(new ArrayAdapter<String>(this,
                        R.layout.item_main_menu, getResources().getStringArray(
                                R.array.main_menu)));
                FragmentTransaction transaction = getSupportFragmentManager()
                        .beginTransaction();
                transaction.add(R.id.content, mMainFragment, MAIN_FRAGMENT_TAG);
                transaction.commit();
            }
            mMainFragment.setOnSelectionChangedListener(this);
    

    you need to set your listeners each time the activity is created to avoid the situation where the fragments have references to old destroyed instances of the activity.

  • 3

    当我按下按钮取消我的 Map 片段活动上的意图选择器时,我得到了这个例外 . 我通过将onResume(我正在初始化片段)的代码替换为onstart()来解决这个问题,并且应用程序工作正常 . 希望它帮助 .

  • 5

    我认为使用 transaction.commitAllowingStateLoss(); 不是最佳解决方案 . 当活动的配置发生更改并且调用片段 onSavedInstanceState() 时,将抛出此异常,此后您的异步回调方法尝试提交片段 .

    简单的解决方案可以检查活动是否正在改变配置

    例如检查 isChangingConfigurations()

    if(!isChangingConfigurations()) { //commit transaction. }

    结帐this链接也是如此

  • 1

    如果你在onActivityResult中做了一些FragmentTransaction,你可以在onActivityResult中设置一些布尔值,然后在onResume中你可以根据布尔值进行FragmentTransaction . 请参考下面的代码 .

    @Override
    protected void onResume() {
        super.onResume;
        if(isSwitchFragment){
            isSwitchFragment=false;
            bottomNavigationView.getTabAt(POS_FEED).select();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FilterActivity.FILTER_REQUEST_EVENT && data != null) {
            isSwitchFragment=true;
        }
    }
    
  • 2

    可能我在我的案例中找到的最顺畅和最简单的解决方案是避免在响应活动结果时将有问题的片段弹出堆栈 . 所以在我的_1077854中更改此调用:

    popMyFragmentAndMoveOn();
    

    对此:

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        public void run() {
            popMyFragmentAndMoveOn();
        }
    }
    

    帮助我的情况 .

  • 18

    每当您尝试在活动中加载片段时,请确保活动处于恢复状态且不会暂停状态 . 在暂停状态下,您可能最终会丢失已完成的提交操作 .

    您可以使用transaction.commitAllowingStateLoss()而不是transaction.commit()来加载片段

    要么

    创建一个布尔值并检查活动是否不会暂停

    @Override
    public void onResume() {
        super.onResume();
        mIsResumed = true;
    }
    
    @Override
    public void onPause() {
        mIsResumed = false;
        super.onPause();
    }
    

    然后加载片段检查

    if(mIsResumed){
    //load the your fragment
    }
    
  • 0

    关于@Anthonyeef很好的答案,这是Java中的示例代码:

    private boolean shouldShowFragmentInOnResume;
    
    private void someMethodThatShowsTheFragment() {
    
        if (this.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) {
            showFragment();
        } else {
            shouldShowFragmentInOnResume = true;
        }
    }
    
    private void showFragment() {
        //Your code here
    }
    
    @Override
    protected void onResume() {
        super.onResume();
    
        if (shouldShowFragmentInOnResume) {
            shouldShowFragmentInOnResume = false;
            showFragment();
        }
    }
    
  • 0

    如果从 FragmentActivity 继承,则必须在 onActivityResult() 中调用超类:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        ...
    }
    

    如果你不't do this and try to show a fragment dialog box in that method, you may get OP' s IllegalStateException . (老实说,我不太明白为什么超级调用会解决问题 . 在 onResume() 之前调用 onActivityResult() ,所以仍然不允许它显示片段对话框 . )

  • 104

    在您的活动中添加此内容

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (outState.isEmpty()) {
            // Work-around for a pre-Android 4.2 bug
            outState.putBoolean("bug:fix", true);
        }
    }
    
  • 1

    从支持库版本24.0.0开始,您可以调用 FragmentTransaction.commitNow() 方法,该方法同步提交此事务,而不是调用 commit() ,然后调用 executePendingTransactions() . 正如documentation所说,这种方法更好:

    调用commitNow比调用commit()后跟executePendingTransactions()更好,因为后者会产生副作用,即尝试提交所有当前挂起的事务,无论这是否是所需的行为 .

  • 12

    我最终创建了一个基本片段,并在我的应用程序中使所有片段扩展它

    public class BaseFragment extends Fragment {
    
        private boolean mStateSaved;
    
        @CallSuper
        @Override
        public void onSaveInstanceState(Bundle outState) {
            mStateSaved = true;
            super.onSaveInstanceState(outState);
        }
    
        /**
         * Version of {@link #show(FragmentManager, String)} that no-ops when an IllegalStateException
         * would otherwise occur.
         */
        public void showAllowingStateLoss(FragmentManager manager, String tag) {
            // API 26 added this convenient method
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (manager.isStateSaved()) {
                    return;
                }
            }
    
            if (mStateSaved) {
                return;
            }
    
            show(manager, tag);
        }
    }
    

    然后,当我尝试显示片段时,我使用 showAllowingStateLoss 而不是 show

    像这样:

    MyFragment.newInstance()
    .showAllowingStateLoss(getFragmentManager(), MY_FRAGMENT.TAG);
    

    我从这个公关中找到了这个解决方案:https://github.com/googlesamples/easypermissions/pull/170/files

  • 10

    另一种可能的解决方法,我不确定在所有情况下是否有帮助(来源here):

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            final View rootView = findViewById(android.R.id.content);
            if (rootView != null) {
                rootView.cancelPendingInputEvents();
            }
        }
    }
    
  • 1

    我知道@Ovidiu Latcu已经接受了答案,但过了一段时间,错误仍然存在 .

    @Override
    protected void onSaveInstanceState(Bundle outState) {
         //No call for super(). Bug on API Level > 11.
    }
    

    Crashlytics仍然向我发送这个奇怪的错误消息 .

    但是现在只出现在版本7(Nougat)上的错误我的修复是在fragmentTransaction中使用 commitAllowingStateLoss() 而不是commit() .

    这个post对commitAllowingStateLoss()有帮助,并且再也没有出现过片段问题 .

    总结一下,这里接受的答案可能适用于前Nougat Android版本 .

    这可能会节省一些人的搜索时间 . 快乐的编码 . <3欢呼

  • 0

    我有同样的问题 . 这是因为以前的活动遭到破坏 . 当ı支持之前的活动时,它被销毁了 . 我把它作为基础活动(错误)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SpinnerCustom2.setFragmentManager(getSupportFragmentManager());
        onCreateDrawerActivity(savedInstanceState);
    }
    

    我把它放在onStart它是正确的

    @Override
    protected void onStart() {
        super.onStart();
        SpinnerCustom2.setFragmentManager(getSupportFragmentManager());
    
    }
    
  • 0

    为了绕过这个问题,我们可以使用在Google I / O 2018中引入的The Navigation Architecture Component . 导航架构组件简化了Android应用程序中导航的实现 .

  • 2

    礼貌:Solution for IllegalStateException

    这个问题困扰了我很多时间,但幸运的是我带来了一个具体的解决方案 . 它的详细解释是here .

    使用commitAllowStateloss()可能会阻止此异常,但会导致UI不规则 . 到目前为止,我们已经理解当我们尝试在Activity状态丢失后提交片段时遇到IllegalStateException - 所以我们应该只延迟事务直到状态恢复这可以简单地完成

    声明两个私有布尔变量

    public class MainActivity extends AppCompatActivity {
    
        //Boolean variable to mark if the transaction is safe
        private boolean isTransactionSafe;
    
        //Boolean variable to mark if there is any transaction pending
        private boolean isTransactionPending;
    

    现在在onPostResume()和onPause中我们设置并取消设置我们的布尔变量isTransactionSafe . 想法是仅在活动处于前景时标记trasnsaction安全,因此不存在状态损失的可能性 .

    /*
    onPostResume is called only when the activity's state is completely restored. In this we will
    set our boolean variable to true. Indicating that transaction is safe now
     */
    public void onPostResume(){
        super.onPostResume();
        isTransactionSafe=true;
    }
    /*
    onPause is called just before the activity moves to background and also before onSaveInstanceState. In this
    we will mark the transaction as unsafe
     */
    
    public void onPause(){
        super.onPause();
        isTransactionSafe=false;
    
    }
    
    private void commitFragment(){
        if(isTransactionSafe) {
            MyFragment myFragment = new MyFragment();
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.frame, myFragment);
            fragmentTransaction.commit();
        }
    }
    
    • 我们到目前为止所做的将从IllegalStateException中保存,但是如果它们在活动转移到后台后完成,那么我们的事务就会丢失,有点像commitAllowStateloss() . 为了帮助我们,我们有isTransactionPending布尔变量
    public void onPostResume(){
       super.onPostResume();
       isTransactionSafe=true;
    /* Here after the activity is restored we check if there is any transaction pending from
    the last restoration
    */
       if (isTransactionPending) {
          commitFragment();
       }
    }
    
    
    private void commitFragment(){
    
     if(isTransactionSafe) {
         MyFragment myFragment = new MyFragment();
         FragmentManager fragmentManager = getFragmentManager();
         FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
         fragmentTransaction.add(R.id.frame, myFragment);
         fragmentTransaction.commit();
         isTransactionPending=false;
     }else {
         /*
         If any transaction is not done because the activity is in background. We set the
         isTransactionPending variable to true so that we can pick this up when we come back to
    foreground
         */
         isTransactionPending=true;
     }
    }
    
  • 0

    抛出此异常(在FragmentActivity中):

    @Override
    public void onBackPressed() {
        if (!mFragments.getSupportFragmentManager().popBackStackImmediate()) {
            super.onBackPressed();
        }
    }
    

    FragmentManager.popBackStatckImmediate() 中,首先调用 FragmentManager.checkStateLoss() . 那是 IllegalStateException 的原因 . 请参阅以下实施:

    private void checkStateLoss() {
        if (mStateSaved) { // Boom!
            throw new IllegalStateException(
                    "Can not perform this action after onSaveInstanceState");
        }
        if (mNoTransactionsBecause != null) {
            throw new IllegalStateException(
                    "Can not perform this action inside of " + mNoTransactionsBecause);
        }
    }
    

    我只需使用标记来标记Activity的当前状态即可解决此问题 . 这是我的解决方案:

    public class MainActivity extends AppCompatActivity {
        /**
         * A flag that marks whether current Activity has saved its instance state
         */
        private boolean mHasSaveInstanceState;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            mHasSaveInstanceState = true;
            super.onSaveInstanceState(outState);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            mHasSaveInstanceState = false;
        }
    
        @Override
        public void onBackPressed() {
            if (!mHasSaveInstanceState) {
                // avoid FragmentManager.checkStateLoss()'s throwing IllegalStateException
                super.onBackPressed();
            }
        }
    }
    

相关问题