【Android】横竖屏切换时生命周期变化
概述:
当横竖屏切换时,可能会引起Activity的重建,以及一些其他的方法调用,用一个demo看看实际的方法调用情况
示例代码:
package com.example.screenswitchtestimport android.content.Intent
import android.content.res.Configuration
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PersistableBundle
import android.util.Logclass MainActivity : AppCompatActivity() {companion object {const val TAG = "MainActivity"}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)Log.w(TAG, "onCreate")}override fun onStart() {super.onStart()Log.w(TAG, "onStart")}override fun onResume() {super.onResume()Log.w(TAG, "onResume")}override fun onPause() {super.onPause()Log.w(TAG, "onPause")}override fun onStop() {super.onStop()Log.w(TAG, "onStop")}override fun onDestroy() {super.onDestroy()Log.w(TAG, "onDestroy")}override fun onRestart() {super.onRestart()Log.w(TAG, "onRestart")}override fun onNewIntent(intent: Intent?) {super.onNewIntent(intent)Log.w(TAG, "onNewIntent")}override fun onSaveInstanceState(outState: Bundle) {super.onSaveInstanceState(outState)Log.w(TAG, "onSaveInstanceState 1 args")}override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {super.onSaveInstanceState(outState, outPersistentState)Log.w(TAG, "onSaveInstanceState 2 args")}override fun onRestoreInstanceState(savedInstanceState: Bundle) {super.onRestoreInstanceState(savedInstanceState)Log.w(TAG, "onRestoreInstanceState 1 args")}override fun onRestoreInstanceState(savedInstanceState: Bundle?,persistentState: PersistableBundle?) {super.onRestoreInstanceState(savedInstanceState, persistentState)Log.w(TAG, "onRestoreInstanceState 2 args")}override fun onConfigurationChanged(newConfig: Configuration) {super.onConfigurationChanged(newConfig)Log.w(TAG, "onConfigurationChanged")}
}
不同配置下的回调情况:
不配置configChanges
启动Activity并切换到横屏

配置configChanges为orientation
启动Activity并切换到横屏

配置configChanges为orientation|screenSize
启动Activity并切换到横屏

结论:
- 不设置configChanges或仅设置为orientation,都不会调用onConfigurationChanged,而是重建Activity触发生命周期回调。
- 在这个重建生命周期过程中,会在onDestroy前执行onSaveInstanceState,在下一次onResume之前执行onRestoreInstanceState。
- 当设置为orientation|screenSize时,会调用onConfigurationChanged,并且不再重建Activity,不触发生命周期回调。
