I am looking for a way to enable night mode programmatically with an Android code:
public static void setNightMode(Context target, boolean state){ UiModeManager uiManager = (UiModeManager) target.getSystemService(Context.UI_MODE_SERVICE); if (state) { //uiManager.enableCarMode(0); uiManager.setNightMode(UiModeManager.MODE_NIGHT_YES); } else { // uiManager.disableCarMode(0); uiManager.setNightMode(UiModeManager.MODE_NIGHT_NO); } }
Nothing has changed on my screen, the night mode is still disables. According to this link
There is no need to enable carMode or deskMode. I have the following logcat on Android Studio:
11-26 12:15:16.662 3823-3823/? D/UiModeManager: updateConfigurationLocked: mDockState=0; mCarMode=false; mNightMode=2; uiMode=33 11-26 12:15:26.802 3823-3823/? V/UiModeManager: updateLocked: null action, mDockState=0, category=null
Turn Dark theme on or off in your phone's settings On your phone, open the Settings app. Tap Display. Turn Dark theme on or off.
Open your device's Settings app . Select Accessibility. Under "Display," turn on Dark theme.
SIMPLEST SOLUTION
You can enable/disable application's dark theme just by:
enable dark theme:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
forcefully disable dark theme:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
set app theme based on mobile settings of dark mode, i.e. if dark mode is enabled then the theme will be set to a dark theme, if not then the default theme, but this will only work in version >= Android version Q (10)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
Notes:
"Theme.AppCompat.DayNight"
like
<style name="DarkTheme" parent="Theme.AppCompat.DayNight"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style>
drawable & drawable-night,
values & values-night
Make sure to change the default theme from Theme.AppCompat.Light.DarkActionBar
to Theme.AppCompat.DayNight.DarkActionBar
in the styles.xml file and then do AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
to switch to the night mode. I have tested it in APIv23(Android 6.0) and above and it is working fine. For a better explanation see this codelab by Android
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