我已经看到了很多关于检测暗模式的问题,比如堆栈溢出上的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。
真的有可能检测到这类设备上强制使用了暗模式吗?
发布于 2021-01-08 00:52:51
经过多次测试,我发现只有在尝试禁用暗模式时才会失败,方法是:
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中描述的
发布于 2020-12-30 06:05:55
根据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 constantsAFAIK,默认为MODE_NIGHT_NO
https://stackoverflow.com/questions/65498309
复制相似问题