I have a LinearLayout that I inflate and add to screen from a service as TYPE_APPLICATION_OVERLAY. This view changes to dark mode when I change the theme from system settings for the whole phone. But when I want to set the night mode manually in my app, this view doesn't change. It only obeys the system theme.
Note that I also have an activity from which I start the service, and I have no trouble setting dark/light mode for that activity manually. But it does not affect the service view, which stays the same as the system theme.
For reference, I have tried AppCompatDelegate methods inside the service, but it doesn't work + plus my activity loses serviceConnection to the service. I have also tried inflating the view with a new ContextThemeWrapper, which did not work either.
Bottom line: How do I manually change the theme for the views added in a foreground/background service?
Try to look here: https://gist.github.com/chrisbanes/bcf4b11154cb59e3f302f278902eb3f7
It is working for me
The code snippet:
fun createNightModeContext(context: Context, isNightMode: Boolean): Context {
val uiModeFlag = if (isNightMode) Configuration.UI_MODE_NIGHT_YES else Configuration.UI_MODE_NIGHT_NO
val config = Configuration(context.resources.configuration)
config.uiMode = uiModeFlag or (config.uiMode and Configuration.UI_MODE_NIGHT_MASK.inv())
return context.createConfigurationContext(config)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With