为什么 Android 会在屏幕旋转时重新启动 activity?

Why does Android restart an activity when screen is rotated?

在我开发的所有应用程序中,我一直在使用

android:configChanges="keyboardHidden|orientation|screenSize"

强制停止Android在屏幕旋转时重新启动Activity。但是最近我在一些诸如 one 之类的 SO 答案中看到了反对这样做的建议。我想知道为什么这是一个糟糕的方法以及为什么 Android 坚持在屏幕旋转时重新启动 activity。

谢谢。

答案在您发布的 link 中的 link 之一

https://developer.android.com/reference/android/app/Activity.html#ConfigurationChanges

This is done because any application resource, including layout files, can change based on any configuration value. Thus the only safe way to handle a configuration change is to re-retrieve all resources, including layouts, drawables, and strings. Because activities must already know how to save their state and re-create themselves from that state, this is a convenient way to have an activity restart itself with a new configuration.

我理解其中一个原因是允许加载横向特定布局的机会

根据the documentation

The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources that match the new device configuration.

所以主要思想是 activity 将使用哪个布局文件的决定是在创建时做出的。

我会说如果配置更改之间没有任何变化,可以使用 (android:configChanges="keyboardHidden|orientation|screenSize"),通过这种方式我们告诉系统,我们正在处理这个方式(或者我们不需要改变任何东西)。 此外,大多数情况下,如果您使用配置更改标志,则不要在代码或 UI.

中更改与它们相关的任何内容

所以没关系,使用配置更改