检测 Android 设备主题(是深色还是浅色)

Nik*_*lai 10 android android-theme

您可以为您的应用设置主题,但我想知道是否可以找出设备使用的是哪个主题。目前,我的应用程序使用Theme.AppCompat.Light. 我想避免改变主题。

PS我已经尝试将其设置为Theme.DeviceDefault并使用反射访问其ID,但到目前为止还没有运气。

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);
}
Run Code Online (Sandbox Code Playgroud)

Sah*_*shi 13

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;
}    
Run Code Online (Sandbox Code Playgroud)