How to set Dark mode for the whole device for Android 10, 11, 12?

Viewed 494

I am trying to create an app that toggles the Dark Mode (Night mode) for the whole system. Not just for my app. I am creating and automation app, so the user decides what to enable or what to disable in just on touch.

To activate the Night mode I do this:

UiModeManager oUiModeManager = (UiModeManager) getApplicationContext().getSystemService(Context.UI_MODE_SERVICE);
oUiModeManager.setNightMode(UiModeManager.MODE_NIGHT_YES); 

and to deactivate I do this:

UiModeManager oUiModeManager = (UiModeManager) getApplicationContext().getSystemService(Context.UI_MODE_SERVICE);
oUiModeManager.setNightMode(UiModeManager.MODE_NIGHT_NO); 

But nothing happens. The dark mode doesn't get activated or deactivated. I have tried with Android 10-Q, Android 11-R and Android 12-S devices. So, how am I supposed to solve this? Remember I need to toggle the whole system dark mode, not just for my app. Thanks

Issue tracker here: https://issuetracker.google.com/issues/173628055 But not answers from Google Developers.

2 Answers

It does not seem that these flags have any effect on the system. The Settings app doesn't use them to switch dark mode.
The method, that the Settings app calls, is hidden, so there is no legal way for an app to call it.
I was able to turn on dark mode on android 11 using this method via reflection with a library to bypass reflection restrictions.

Android offical has a sample DarkTheme.But I don't know if it works

Related