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

329 views Asked by At

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?

2

There are 2 answers

0
RufusInZen On

After days of research and trials, I have concluded that this is not possible. It all comes down to what context is used in the service. According to this question with many detailed answers, service context cannot inflate layouts with custom themes, the system will always inflate them with the default system theme.

If anyone finds a way, I'll be happy to learn.

0
ferdinand On

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)
}