Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppCompatDelegate.setDefaultNightMode() picked up by main activity only the first time?

Running Android P, using androidx 1.0.0 (minSdkVersion 17). From my MainActivity I open my PreferenceActivity. There I change the UI theme, and also re-create the activity to pick up the changes:

AppCompatDelegate.setDefaultNightMode(nightMode);
recreate();

After updating the theme, I return to MainActivity. There the theme is successfully updated. Then I re-open the PreferenceActivity and change the theme again.

So far so good!

Finally, I return to the MainActivity again. The theme is NOT updated, and it will not update if you repeat the steps!

Thus, the steps to reproduce seem to be:

  1. From activity A, open activity B.
  2. In B, call AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES) and then recreate(). Theme is updated!
  3. Return to A. Theme is updated!
  4. Open activity B again.
  5. In B, call AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO) and then recreate(). Theme is updated!
  6. Return to A. Theme is NOT updated and will NOT update if steps 3-6 are repeated!

I tried calling recreate() when returing from the PreferenceActivity but that yields another problem when the library does react on the theme change:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (...) {
        recreate();
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

That works when the library does NOT react on the updated theme. Otherwise the activity is recreated twice (possibly more when debugging), which kills performance etc:

D/MainActivity: onActivityResult(): instance 1
D/MainActivity: onResume(): instance 1
D/MainActivity: onPause(): instance 1
D/MainActivity: onDestroy(): instance 1

D/MainActivity: onCreate(): instance 2
D/MainActivity: onResume(): instance 2
D/MainActivity: onPause(): instance 2
D/MainActivity: onDestroy(): instance 2

D/MainActivity: onCreate(): instance 3
D/MainActivity: onResume(): instance 3

Q: What is going on with the setDefaultNightMode() API? And more importantly, how can I successfully update all running activities without the risk of re-creating them multiple times?

UPDATE

There is a sample project demonstrating the issue here: https://issuetracker.google.com/issues/119757688

like image 497
l33t Avatar asked Nov 17 '18 23:11

l33t


1 Answers

When you change night Mode, store the mode value to shared preference.

AppCompatDelegate.setDefaultNightMode(nightMode);
recreate(); //only recreate setting activity 
...//store mode value, these lines are omitted,please complete yourself

In other activity onCreate() method:

...//get mode from share preference, these lines are omitted.
AppCompatDelegate.setDefaultNightMode(mode)//must place before super.onCreate();
super.onCreate(savedInstanceState);
like image 80
navylover Avatar answered Oct 19 '22 22:10

navylover