我看到很多关于检测黑暗模式的问题,比如 this one在堆栈溢出上访问了许多媒体博客,如 How to know when you’re using dark mode programmatically和 DayNight — Adding a dark theme to your app在所有这些中,他们都执行这样的检查:
fun isNightModeEnabled(context: Context): Boolean =
context.resources.configuration.uiMode.and(UI_MODE_NIGHT_MASK) ==
UI_MODE_NIGHT_YES
这适用于任何手机,甚至是运行 Android One 的小米手机,但不适用于运行 MIUI 的小米智能手机。
对于运行 MIUI 的小米设备:
context.resources.configuration.uiMode
= 17
和context.resources.configuration.uiMode.and(UI_MODE_NIGHT_MASK)
= 16
与 UI_MODE_NIGHT_YES (32)
相比,在启用或禁用暗模式时始终返回 false。
是否真的可以检测到此类设备已强制进入深色模式?
最佳答案
经过多次测试,我发现只有在尝试通过以下方式禁用暗模式时才会失败:
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO)
在那种情况下,该方法错误地返回它未处于黑暗模式。 所以我所做的是在应用程序主题上也强制禁用暗模式:
<item name="android:forceDarkAllowed">false</item>
这真的停止了带有 MIUI 的设备的黑暗模式。
如果您不想禁止暗模式,则通过前面提到的方式检测当前主题应该没有问题:
val currentNightMode = configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
when (currentNightMode) {
Configuration.UI_MODE_NIGHT_NO -> {} // Night mode is not active, we're using the light theme
Configuration.UI_MODE_NIGHT_YES -> {} // Night mode is active, we're using dark theme
}
这是 docs 中描述的那个
关于android - 在miui(小米)中检测暗模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65498309/