Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System applies night mode to views added in service (TYPE_APPLICATION_OVERLAY), but how to apply night mode manually?

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?

like image 563
RufusInZen Avatar asked Dec 05 '25 10:12

RufusInZen


1 Answers

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)
}
like image 62
ferdinand Avatar answered Dec 08 '25 00:12

ferdinand