且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何防止在Android上按下电源按钮时先调用onDestroy()再调用onCreate()

更新时间:2023-12-02 23:05:16

按下电源按钮时,通常会启动屏幕锁定.这可能会触发当前前台活动的配置更改(通常是屏幕锁定在纵向模式下),导致它被销毁并重新创建.

When you press the power button, the screen lock usually kicks in. This may trigger a configuration change on the activity currently in the foreground (the screen lock is usually in portrait mode), causing it to be destroyed and recreated.

在AndroidManifest.xml中为此类活动声明android:configChanges="keyboardHidden|orientation"可以防止销毁这些活动并重新创建它们,但也意味着您可以通过覆盖

Declaring android:configChanges="keyboardHidden|orientation" for such activities in AndroidManifest.xml prevents them to be destroyed and recreated but also implies that you will handle the configuration changes by yourself (if necessary) by overriding onConfigurationChanged