androidxiaomimiuiandroid-darkmode

Detect dark mode in miui (xiaomi)


I have seen many questions about detecting the dark mode like this one on stack overflow and visited many medium blogs like How to know when you’re using dark mode programmatically and DayNight — Adding a dark theme to your app and in all of them they perform a check like this one:

fun isNightModeEnabled(context: Context): Boolean =
    context.resources.configuration.uiMode.and(UI_MODE_NIGHT_MASK) ==
            UI_MODE_NIGHT_YES

and this works well in any phone and even the Xiaomi mobiles that run Android One but not on the Xiaomi smartphones that run MIUI.

For Xiaomi devices running MIUI:

context.resources.configuration.uiMode = 17

and context.resources.configuration.uiMode.and(UI_MODE_NIGHT_MASK) = 16

Which compared to UI_MODE_NIGHT_YES (32) always returns false with dark mode enabled or disabled.

Is it really possible to detect that the dark mode has been forced on such devices?


Solution

  • Turned out after many tests I found out it only failed when trying to disable dark mode by doing:

    AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO)
    

    In that case the method wrongly returned that it was not on dark mode. So what I did is to force disable dark mode also on the app theme:

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

    And this really stops dark mode for devices with MIUI.

    In case you don't want to disallow dark mode you shouldn't have problems detecting the current theme by that way previously mentioned:

    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
    }
    

    which is the one described in the docs