Search code examples
androidandroid-appcompatandroid-resourcesandroid-night-mode

Activity is recreated when screen rotation changes if-and-only-if Night Mode is ON


I have this Activity (subclass of AppCompatActivity):

<activity
    android:name=".ui.settings.SettingsActivity"
    android:configChanges="keyboardHidden|smallestScreenSize|orientation|screenSize|screenLayout"
    android:launchMode="singleTask"
    android:parentActivityName=".ui.main.MainActivity" />

Now, when I rotate the phone while in normal (i. e. "Day") mode I get a call to onConfigurationChanged but the Activity is not re-created.

However, when the app is set to Night Mode (by calling AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) in my Application before the Activity is created) and I then rotate the phone, I first get a call to onConfigurationChanged but then the Activity is also re-created, even though the uiMode has not changed at all! This goes away when I add uiMode to the configChanges that should be ignored in my AndroidManifest.xml, but it seems weird that I need to do this.

From looking through the source it seems that:

  • onConfigurationChanged calls getDelegate().onConfigurationChanged(newConfig); which goes to AppCompatDelegateImpl.onConfigurationChanged(newConfig)
  • there, applyDayNight() gets called
  • there, getNightMode returns AppCompatDelegateImpl.MODE_NIGHT_YES, which makes sense since this is what I set it to. mapNightMode just returns that value unchanged. Then updateForNightMode(AppCompatDelegateImpl.MODE_NIGHT_YES) gets called
  • there, newNightMode is calculated correctly to be Configuration.UI_MODE_NIGHT_YES but currentNightMode (which is read in from mContext.getResources().getConfiguration().uiMode) always appears to be Configuration.UI_MODE_NIGHT_NO after each rotation, even if the Activity was rendered in Night Mode before the rotation.

So, what's going on here and what could I do to get more consistent behavior? (Re-create (or not) the Activity after a screen rotation, regardless of whether the app is in Night Mode or not.)


Solution

  • Seems to be a bug and will be fixed in AppCompat v1.1.0 according to this issue.

    Starting with AppCompat v1.1.0-alpha03 you no longer need the uiMode-flag in the configChanges as a workaround