Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect the Android device theme (is it dark or light)

You can set the theme for your app, but I'm wondering if it's possible to find out which one is used by the device. Currently, my app uses Theme.AppCompat.Light. I'd like to avoid changing the theme.

P.S. I've already tried to set it to Theme.DeviceDefault and access its ID using reflection, but no luck so far.

try {
    setTheme(android.R.style.Theme_DeviceDefault);

    Class<Context> contextClass = Context.class;
    Method getThemeMethod = contextClass.getMethod("getThemeResId");
    getThemeMethod.setAccessible(true);
    Log.d("Test", "" + getThemeMethod.invoke(this)); // Always returns 0

    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
    Log.d("Test", getResources().getResourceEntryName(packageInfo.applicationInfo.theme)); // Returns 'Theme.DeviceDefault'
} catch (Exception e) {
    Log.d("Test", "exception", e);
}
like image 507
Nikolai Avatar asked Nov 01 '16 09:11

Nikolai


2 Answers

int currentNightMode = getContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;  
switch (currentNightMode) {
    case Configuration.UI_MODE_NIGHT_NO:
        // Night mode is not active on device
        break;
    case Configuration.UI_MODE_NIGHT_YES:
        // Night mode is active on device
        break;
}    
like image 63
Sahil Doshi Avatar answered Oct 08 '22 12:10

Sahil Doshi


This might help ContextThemeWrapper

like image 45
Shubham Sharma Avatar answered Oct 08 '22 14:10

Shubham Sharma