android-studioclasscastexceptionandroid-dark-thememiuidarkmode

MIUI 11/12 Theme Switch Results in LifeCycleException, ClassCastException


Since MIUI 11/12 Use Its Own Custom Implementation of Dark Mode, using below code results in ClassCastException and Activity Life Cycle Exception, as DefaultNightMode and LocalNightMode is always Unspecified i.e. -100 instead of 0 or 1.

If anyone has built a workaround for Xiaomi Devices specially for MIUI 11/12. Please Help Me Out On this.

Code Used:

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
this.recreate();

Error Caused:

2020-10-25 07:04:43.626 9167-9167/com.xxxx.xxxxxx E/ActivityInjector: get life cycle exception
    java.lang.ClassCastException: android.os.BinderProxy cannot be cast to android.app.servertransaction.ClientTransaction

Solution

  • I solved it myself. After fiddling around with it for a week, I did it..

    Here is how:

    -- Instead of setting android:forceDarkAllowed="false" for each and every Activity.

    -- Just goto values.xml and place this in your AppTheme

            <item name="android:forceDarkAllowed">false</item>
    

    It will ask you to create a valuesv29.xml. Create it, and remove the forceDarkAllowed="false" from all activities.

    Welcome. :)