安卓横竖屏切换时候Activity的生命周期

一定要亲自动手测试,切勿轻信网上的复制粘贴。

0x01 Activity不同过程的生命周期

1.1 启动

onCreate
onStart
onResume

1.2 停止

onPause
onDestroy

1.3重建

就是先停止,再启动
onPause
onDestroy
onCreate
onStart
onResume

1.4包含保存状态的重建

1.4.1 3.0及以后

onPause
onSaveInstanceState
onDestroy
onCreate
onStart
onRestoreInstanceState
onResume

1.4.2 3.0以前(API11以前,不包括3.0)

按理说应该是onSaveInstanceState在onPause之前,执行的是
onSaveInstanceState
onPause
onDestroy
onCreate
onStart
onRestoreInstanceState
onResume
但是实测的时候居然什么也没有,好像没有重建?罢了,这个不重要,只要知道3.0以前不一样就行了。
原因见Activity Lifecycle

Be aware that these semantics will change slightly between applications targeting platforms starting with HONEYCOMB vs. those targeting prior platforms. Starting with Honeycomb, an application is not in the killable state until its onStop() has returned. This impacts when onSaveInstanceState(Bundle) may be called (it may be safely called after onPause() and allows and application to safely wait until onStop() to save persistent state.

1.5不重建切换时的生命周期

onConfigurationChanged

0x02 切换时执行什么过程

2.1 默认情况

默认情况下,横竖屏切换会执行重建,即1.4

2.2 设置了android:configChanges=”orientation”

2.2.1 在3.2及以上(API13)

由于还需要screenSize,所以重建,执行1.4

2.2.2 在3.2以下

不重建。执行1.5
原因见处理运行时变更

注意:从 Android 3.2(API 级别 13)开始,当设备在纵向和横向之间切换时,“屏幕尺寸”也会发生变化。因此,在开发针对 API 级别 13 或更高版本系统的应用时,若要避免由于设备方向改变而导致运行时重启(正如 minSdkVersion 和 targetSdkVersion 属性中所声明),则除了 “orientation” 值以外,您还必须添加 “screenSize” 值。即,您必须声明 android:configChanges=”orientation|screenSize”。但是,如果您的应用是面向 API 级别 12 或更低版本的系统,则 Activity 始终会自行处理此配置变更(即便是在 Android 3.2 或更高版本的设备上运行,此配置变更也不会重启 Activity)。

2.3 设置了android:configChanges=”orientation|screenSize”

这样就包括3.2以下和以上了,执秆1.5.

2.4 keyboardHidden

设个是The keyboard accessibility has changed — for example, the user has revealed the hardware keyboard.
虽然也经常设置在android:configChanges里面,但好像根横竖屏无关啊。

android:configChanges="orientation|screenSize|keyboardHidden"

0x03 参考方献

[1]处理运行时变更
[2]你还在问android横竖屏切换的生命周期?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值