在miui小米中检测暗模式

问题描述

我看到很多关于检测暗模式(如堆栈溢出时的 this one)的问题,并访问了许多中等博客(如 How to know when you’re using dark mode programmaticallyDayNight — 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。

是否真的可以检测到此类设备已强制启用暗模式?

解决方法

经过多次测试,我发现它仅在尝试禁用暗模式时失败:

leftHeader

在那种情况下,该方法错误地返回它不在暗模式下。 所以我所做的是在应用主题上也强制禁用暗模式:

AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO)

这确实停止了带有 MIUI 的设备的暗模式。

如果您不想禁用暗模式,则通过前面提到的方式检测当前主题应该不会有问题:

<item name="android:forceDarkAllowed">false</item>

这是docs

中描述的 ,

根据 Chris Banes 的文章,还有另一种方法。

设置模式(暗或亮):

AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES) // or MODE_NIGHT_NO or MODE_NIGHT_AUTO for system defaults

然后你就可以玩资源,黑暗或光明。不确定这种从上下文检查暗模式的方式是否仍然相关。我没有这些信息。

按照上面的逻辑,检查应用程序是否处于黑暗模式:

if (AppCompatDelegate.getDefaultNightMode() == MODE_NIGHT_YES) //or other constants

AFAIK,默认是 MODE_NIGHT_NO