Android commit 和 commitAllowingS

作者: chenxuxu | 来源:发表于2018-04-22 22:11 被阅读50次
    1615230-60be89c602040f87.jpg

    fragment 基本上是每个项目都会用到,一般我们会这么写:

        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fragment_container, new MyFragment())
                .commit();
    

    但是有时候会报如下错误信息:

        Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
    

    意思就是说我们不能在调用onSaveInstanceState进行commit操作。网上的解决办法是使用commitAllowingStateLoss替换commit。确实是不报错了,但是为什么呢?

    来,开始我们的侦探之旅吧!(有点绕,请一步步往下看)

    首先找到FragmentTransaction类。

        public abstract class FragmentTransaction {
            public abstract int commit();
            public abstract int commitAllowingStateLoss();
        }
    

    原来commitcommitAllowingStateLoss是抽象方法。继续往下找。

        final class BackStackRecord extends FragmentTransaction implements
                FragmentManager.BackStackEntry, FragmentManagerImpl.OpGenerator {
            @Override
            public int commit() {
                return commitInternal(false);
            }
    
            @Override
            public int commitAllowingStateLoss() {
                return commitInternal(true);
            }
        }
    

    发现BackStackRecord类继承了FragmentTransaction。可以看出,不同之处只有commitInternal的参数。感觉离真相又近了一步,继续往下看:

        int commitInternal(boolean allowStateLoss) {    
            // ...不显示无关代码
            mManager.enqueueAction(this, allowStateLoss);
            return mIndex;
        }
    

    commitInternal方法内,只有mManager.enqueueAction(this, allowStateLoss);使用了该布尔值参数。离真相还差一点了,继续推测:

        public void enqueueAction(OpGenerator action, boolean allowStateLoss) {
            if (!allowStateLoss) {
                checkStateLoss();
            }
            synchronized (this) {
                if (mDestroyed || mHost == null) {
                    if (allowStateLoss) {
                        // This FragmentManager isn't attached, so drop the entire transaction.
                        return;
                    }
                    throw new IllegalStateException("Activity has been destroyed");
                }
                // ...无关代码
            }
        }
    

    有了突破性进展!此处对allowStateLoss值进行了判断。checkStateLoss按照命名意思是校验状态。离真相仅剩一步了!

        private void checkStateLoss() {
            if (isStateSaved()) {
                throw new IllegalStateException(
                        "Can not perform this action after onSaveInstanceState");
            }
            if (mNoTransactionsBecause != null) {
                throw new IllegalStateException(
                        "Can not perform this action inside of " + mNoTransactionsBecause);
            }
        }
    
        @Override
        public boolean isStateSaved() {
            // See saveAllState() for the explanation of this.  We do this for
            // all platform versions, to keep our behavior more consistent between
            // them.
            return mStateSaved || mStopped;
        }
    

    这里会抛出异常信息,明显就是文章开头碰到的异常错误信息!isStateSaved()方法也一同显示了。到了此时,可以明白commit是会对状态进行检测,并抛出异常;而commitAllowingStateLoss方法只是不进行状态检测,因此不会抛出异常。这明显是有点逃避问题,那么这个状态是什么判断而得出的呢?

        Parcelable saveAllState() {
            // ...无关代码
            mStateSaved = true;
            // ...无关代码
        }
    

    我们主要看mStateSaved变量。在saveAllState 方法内,把mStateSaved赋值为 true。有意思的是saveAllState是在ActivityFragmentActivity内的onSaveInstanceState方法调用的。

    总结:

    有点绕~最后在此理顺整体思路:在ActivityFragmentActivity内的onSaveInstanceState方法保存了fragment的状态。在onSaveInstanceState方法后调用commitcommitAllowingStateLoss会引起一种问题:因内存不足而把不显示在前台的 activity (带有 fragment)销毁,之后用户再回到此 activity 页面时,是会丢失在onSaveInstanceState后调用commit方法提交的页面状态信息!
    不同的只是调用commit会报错,调用commitAllowingStateLoss不报错(睁一只眼闭一只眼)。

    谷歌在commitAllowingStateLoss方法的注释上也写明,调用此方法会有丢失页面状态信息的风险。

    Like {@link #commit} but allows the commit to be executed after an
    activity's state is saved. This is dangerous because the commit can
    be lost if the activity needs to later be restored from its state, so
    this should only be used for cases where it is okay for the UI state
    to change unexpectedly on the user.

    1. 一般情况下,尽量提早调用 commit 方法,比如说onCreate()
    2. 异步回调中避免使用commit
    3. 不得已的情况,可以使用commitAllowingStateLoss替代commit。毕竟报错奔溃,比页面状态信息丢失更严重;

    推荐:

    Android commit 和 commitAllowingStateLoss 区别及应用场景

    相关文章

      网友评论

        本文标题:Android commit 和 commitAllowingS

        本文链接:https://www.haomeiwen.com/subject/mdlwkftx.html