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:
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES) and then recreate(). Theme is updated!AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO) and then recreate(). Theme is updated!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?
There is a sample project demonstrating the issue here: https://issuetracker.google.com/issues/119757688
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With