Reputation: 1396
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?
Upvotes: 2
Views: 2191
Reputation: 1396
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
Upvotes: 7
Reputation: 8371
According to Chris Banes article there is another way to go for it.
Set mode (either dark or light):
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES) // or MODE_NIGHT_NO or MODE_NIGHT_AUTO for system defaults
Then you can just play with resources, dark or light. Not sure if this way of checking dark mode from context is still relevant. I do not have that information.
Following the logic above, to check if the app is in dark mode:
if (AppCompatDelegate.getDefaultNightMode() == MODE_NIGHT_YES) //or other constants
AFAIK, the default one is MODE_NIGHT_NO
Upvotes: 0