日常积累

2018-11-12  本文已影响9人  niknowzcd

commit和commitAllowingStateLoss区别

是否检测宿主activity是否调用过onSaveInstanceState()

如果onSaveInstanceState()已经被调用,这时会抛出一个异常.

Can not perform this action after onSaveInstanceState");

那么为什么在commit的过程中需要检测onSaveInstanceState()的状态呢?

因为在onSaveInstanceState()之后commit的事务不会被系统所保存.这可能就会导致一些ui或者数据的偏差

参考文章

Activity状态的保存和恢复

activity分正常销毁(返回键或者Home键)和非正常销毁(内存不足被回收)

非正常销毁的情况下,系统默认会保存Activity视图层次的状态信息,包括视图对象中的数据,比如(EditText中的输入值,或者listView当前滚动的位置),

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first

    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...
}

或者在 onStart()之后调用 onRestoreInstanceState()

public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);

    // Restore state members from saved instance
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}

查看当前Activity是否调用过onSaveInstanceState()可以通过 isStateSaved()方法来判断

注意:isStateSaved()从support-26.0.0开始,并且只在Fragment以及FragmentManager中提供了

另外当Activity调用过onSaveInstanceState()之后,诸如Fragment的事务或者Intent的跳转之类的操作都是不被允许的。

参考文章

处理运行时变更

Fragment调用setRetainInstance的原理

http和https的区别

判断fragment是否可见 setUserVisibleHint和onHiddenChanged使用场景

https://blog.csdn.net/kristch_wu/article/details/80000148

上一篇下一篇

猜你喜欢

热点阅读