Android Activity横竖屏切换生命周期

面试被问到横竖屏切换时Activity的生命周期,正好记录一下验证过程~

横竖屏切换涉及到的是Activity的android:configChanges属性,而与其android:launchMode属性没有关系;
android:configChanges可以设置的属性值有:

  1. orientation:消除横竖屏的影响
  2. keyboardHidden:消除键盘的影响
  3. screenSize:消除屏幕大小的影响
验证步骤

新建Activity,重写各个生命周期方法:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("TAG", "onCreate()");
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("TAG", "onStart()");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("TAG", "onResume()");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("TAG", "onStop()");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("TAG", "onPause()");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("TAG", "onRestart()");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("TAG", "onDestroy()");
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.d("TAG", "onRestoreInstanceState()");
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.d("TAG", "onSaveInstanceState()");
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d("TAG", "onConfigurationChanged()");
    }
}

运行Activity,生命周期如下:

image

切换横屏,生命周期如下:

image

再切回竖屏,生命周期如下:

image

修改AndroidManifest.xml,添加android:configChanges="orientation"并切换横屏,生命周期如下:

image

再切换竖屏,生命周期如下:

image

修改AndroidManifest.xml,属性改为android:configChanges="orientation|keyboardHidden|screenSize",切换横屏,生命周期如下:

image

再切换回竖屏,生命周期如下:

image
结论
  1. 设置Activity的android:configChanges属性为orientation或者orientation|keyboardHidden或者不设置这个属性的时候,横竖屏切换会重新调用各个生命周期方法,切横屏时会执行1次,切竖屏时会执行1次;
  2. 设置Activity的属性为android:configChanges="orientation|keyboardHidden|screenSize"时,横竖屏切换不会重新调用各个生命周期方法,只会执行onConfigurationChanged方法;
  3. 当然在显示中我们可以屏蔽掉横竖屏的切换操作,这样就不会出现切换的过程中Activity生命周期重新加载的情况了,具体做法是,在Activity中加入如下语句:
    android:screenOrientation="portrait" 始终以竖屏显示
    android:screenOrientation="landscape" 始终以横屏显示

作者:sybil052
链接:https://www.jianshu.com/p/479457823277
来源:
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(Android Activity横竖屏切换生命周期)