美文网首页
Android 基础:Fragment 各种 Commit 使用

Android 基础:Fragment 各种 Commit 使用

作者: 红发_SHANKS | 来源:发表于2018-07-11 14:10 被阅读150次

    FragmentTransaction 中的 Commit 方法

    • commit():int
    • commitAllowingStateLoss():int
    • commitNow():void
    • commitNowAllowingStateLoss():void

    commit 方法

    文档注释:

    * Schedules a commit of this transaction.  The commit does
    * not happen immediately; it will be scheduled as work on the main thread
    * to be done the next time that thread is ready.
    *
    * <p class="note">A transaction can only be committed with this method
    * prior to(prior to 前于) its containing activity saving its state.  If the commit is
    * attempted after that point, an exception will be thrown.  This is
    * because the state after the commit can be lost if the activity needs to
    * be restored from its state.  See {@link #commitAllowingStateLoss()} for
    * situations where it may be okay to lose the commit.</p>
    * 
    * @return Returns the identifier(标识符) of this transaction's back stack entry,
    * if {@link #addToBackStack(String)} had been called.  Otherwise, returns
    * a negative number.
    

    从文档中我们知道:
    commit 方法并非一个立即执行的方法,他需要等待线程准备好了再执行(如果需要立即执行则调用executePendingTransactions())。

    commit 方法必须要在 fragment 的容器 Activity 执行 onSavaInstance() 方法之前执行(onSaveInstanceState() 方法在 onStop() 方法之前执行,确保 Activity 因为各种原因被系统杀掉后能正确的保存和恢复状态,onSaveInstanceState() 方法 和 onPause() 方法之间没有必然的执行先后顺序),否则会抛出异常(IllegalStateException("Can not perform this action after onSaveInstanceState"))。因为在 Activity 执行了 onSaveInstanceState() 方法之后再执行 commit 方法的话,Fragment 的状态就丢失了,在官方看来这是很危险的,如果我们不在乎 Fragment 的状态的话,官方推荐使用 commitAllowingStateLoss() 方法。

    使用注意事项和源代码解析###

    • 在 Activity 中调用 commit() 方法的时候,应该注意在 onCreate() 或者是在 FragmentActivity#onResume()/Activity#onPostResume() 中调用。后者是保证 Activity 的状态已经完全恢复,避免出现 IllegalStateException.
    • 避免在异步任务中调用 commit,因为异步任务不能确保Activity的状态,如果 Activity 已经调用 onStop() 方法,此时再 Commit() 就会报错。
    • 如果不在乎 Fragment 状态丢失,可以使用 commitAllowingStateLoss() 方法。
    • 同一个 transaction 中只能调用一次 commit()

    源码解析###

    查看源码,可以看到 commit 方法调用的是 commitInternal(boolean allowStateLoss):int 方法

    @Override
    public int commit() {
        return commitInternal(false);
    }
    

    查看 commitInternal(boolean allowStateLoss):int 方法

    int commitInternal(boolean allowStateLoss) {
        // 首先会检查是否已经进行过 commit,所以 Commit 方法只能在同一个 transaction 中调用一次
        if (mCommitted) throw new IllegalStateException("commit already called");
        if (FragmentManagerImpl.DEBUG) {
            Log.v(TAG, "Commit: " + this);
            LogWriter logw = new LogWriter(TAG);
            PrintWriter pw = new PrintWriter(logw);
            dump("  ", null, pw, null);
            pw.close();
        }
        mCommitted = true;
        if (mAddToBackStack) {
            mIndex = mManager.allocBackStackIndex(this);
        } else {
            mIndex = -1;
        }
        mManager.enqueueAction(this, allowStateLoss);
        // 证实了注释中说的,如果没有加入返回栈那么返回一个负数
        return mIndex;
    }
    

    继续进入 enqueueAction 方法,我们看到了 checkStateLoss() 方法。

        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");
                }
                if (mPendingActions == null) {
                    mPendingActions = new ArrayList<>();
                }
                mPendingActions.add(action);
                scheduleCommit();
            }
        }
    

    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;
        }
    

    由此,我们明白了 Commit 可能产生的两个异常是如何发生的,以及如何避免这样的异常。

    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.
    */
    

    源码:和 commit() 方法调用的是同一个方法,但是设置了可忽略状态。从 commit() 方法的流程中我们可以看出,使用 commitAllowingStateLoss()确实可以避免发生状态丢失的异常,但是我们在使用的时候,还是应该尽量少使用这个方法,而是正确、安全的使用 commit(),使问题能够得到正确的解决。

    @Override
    public int commitAllowingStateLoss() {
        return commitInternal(true);
    }
    

    commitNow##

    注释:

    * <p>Calling <code>commitNow</code> is preferable to calling
    * {@link #commit()} followed by {@link FragmentManager#executePendingTransactions()}
    * ...
    *  * This method will throw {@link IllegalStateException} if the transaction
    * previously requested to be added to the back stack with
    * {@link #addToBackStack(String)}.</p>
    * ...
    * <p class="note">A transaction can only be committed with this method
    * prior to its containing activity saving its state.  If the commit is
    * attempted after that point, an exception will be thrown.  This is
    * because the state after the commit can be lost if the activity needs to
    * be restored from its state.  See {@link #commitAllowingStateLoss()} for
    * situations where it may be okay to lose the commit.</p>
    */
    

    从注释中,我们知道,commitNow()方法是立即执行,而不是等待 Activity 的 Handler 准备好了。commitNow()方法产生的 Fragment 不能添加到回退栈。和 commit() 方法 一样,会检查 Activity 的状态。

    源码解读:

    @Override
    public void commitNow() {
        // 禁止添加到回退栈
        disallowAddToBackStack();
        mManager.execSingleAction(this, false);
    }
    
    @Override
    public FragmentTransaction disallowAddToBackStack() {
        if (mAddToBackStack) {
            throw new IllegalStateException(
                    "This transaction is already being added to the back stack");
        }
        mAllowAddToBackStack = false;
        return this;
    }
    

    CommitNowAllowingStateLoss##

    除了不检查 Activity 的状态以外,其他方面和 CommitNow一样

    @Override
    public void commitNowAllowingStateLoss() {
        disallowAddToBackStack();
        mManager.execSingleAction(this, true);
    }
    

    相关文章

      网友评论

          本文标题:Android 基础:Fragment 各种 Commit 使用

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