Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

android - How to enable night mode programmatically?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

SIMPLEST SOLUTION

You can enable/disable application's dark theme just by:

  1. enable dark theme:

     AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
    
  2. forcefully disable dark theme:

     AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
    
  3. 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:

  1. Your base theme for app/activity should be

"Theme.AppCompat.DayNight"

like

<style name="DarkTheme" parent="Theme.AppCompat.DayNight">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
  1. Your res folder's names would end with -night so that different colors and images you can set for day and night themes like

drawable & drawable-night,
values & values-night


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...