【问题标题】:Detect dark mode in miui (xiaomi)在miui(小米)中检测暗模式
【发布时间】:2021-04-06 10:43:04
【问题描述】:

我看到了很多关于在堆栈溢出时检测暗模式的问题,例如 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。

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

【问题讨论】:

    标签: android xiaomi miui android-darkmode


    【解决方案1】:

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

    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中描述的那个

    【讨论】:

    • 我在任何地方都找不到这行代码&lt;item name="android:forceDarkAllowed"&gt;false&lt;/item&gt;。这种情况我该怎么办?
    • 您应该将其添加到您正在使用的应用程序主题中,以防您想强制禁用暗模式。如果您想知道,应用程序使用的主题可能会在 android 清单中设置。如果它不是自定义的,请在您的 styles.xml 文件中扩展它并在其中设置 forceDarkAllowed 并在您的活动中使用该扩展的。
    【解决方案2】:

    根据 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

    【讨论】:

    • 感谢您的回答,非常感谢。但是,它似乎不起作用:(我开始认为这可能是因为这种暗模式是由操作系统强制的,但我不知道这似乎不起作用的原因是什么。
    • 如果是操作系统强制的,你应该先把它设置为'MODE_NIGHT_AUTO'然后问问题(if语句)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多