Starting with Android 10, it became possible to change the device theme from settings (to dark and light), and the application by default grasps the theme that is set in the system. But I ran into a rather interesting problem. A device with Android 9 and in the settings there is also the possibility of changing the theme, but when I use a dark theme, nothing happens and my application remains in the light theme. I read on the Internet and found a way to get a theme(is light):
private fun foo(): Boolean {
return resources.configuration.uiMode and
Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_NO
}
, but this function always returns that a light theme has been applied (in Android 9 when a dark theme is enabled in the settings). As far as I understood, this is because this function returns the theme that is in the application and wanted to find out how, in this case, you can get the theme of the system.
The resources associated with the Activity will reflect the configuration of that Activity. That means that
resources.configuration(or anycontext.resources.configuration) will have theuiModeof your Activity, not of the System.When your application is starting, Android must create the
Applicationinstance for your app. At this moment your resources are not loaded yet, so Android attaches resources and configuration of the System to yourApplicationinstance. So you can access theuiModeof the System from the application Context. Also, you can access System resources and configuration usingResources.getSystem(), which is handy when you don't have access to anyContext.