I am using the AppCompatDelegate.setDefaultNightMode(mode);
to set the Night Mode in my Android Application, whenever the user chooses any mode that preference configuration in the Shared Preferences on their device, now while I use the shared preferences to set the UI mode when the app starts from the Splash Screen Activity, the activity is getting recreated and then there are 2 instances of my app, as the Splash Screen intents to Landing Activity.
Here is my SplashScreen.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
SharedPreferences prefs = getSharedPreferences(UI_MODE, MODE_PRIVATE);
name = prefs.getString("uiMode", "System");
applyUI();
fireSplashScreen();
}
private void applyUI() {
if (name.equals("Dark")){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else if (name.equals("Light")){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}
private void fireSplashScreen() {
Intent i = new Intent(SplashScreen.this, Landing.class);
startActivity(i);
finish();
}
What can I do to avoid creating multiple instances of the Landing Activity?
Make sure to call AppCompatDelegate.setDefaultNightMode()
as soon as possible. E.g. before calling super.onCreate()
. Ideally, you would want to call it in Application.onCreate()
. Also, make sure to use the latest version of AppCompat
(at least 1.1.0) or you might face this issue anyway.
See this answer for more details.