androidandroid-night-mode

Android - How to detect if night mode is on when using AppCompatDelegate.MODE_NIGHT_AUTO


I'm using Androids built in day/night mode functionality and I'd like to add an option to my app for AppCompatDelegate.MODE_NIGHT_AUTO

I'm having a problem though because my app requires certain things to be colored programmatically, and I can't figure out how to check if the app considers itself in night or day mode. Without that, I can't set a flag to choose the right colors.

Calling AppCompatDelegate.getDefaultNightMode() just returns AppCompatDelegate.MODE_NIGHT_AUTO which is useless.

I don't see anything else that would tell me, but there must be something?


Solution

  • int nightModeFlags =
        getContext().getResources().getConfiguration().uiMode &
        Configuration.UI_MODE_NIGHT_MASK;
    switch (nightModeFlags) {
        case Configuration.UI_MODE_NIGHT_YES:
             doStuff();
             break;
    
        case Configuration.UI_MODE_NIGHT_NO:
             doStuff();
             break;
    
        case Configuration.UI_MODE_NIGHT_UNDEFINED:
             doStuff();
             break;
    }