调用 AppCompatDelegate.setDefaultNightMode 后重新创建启动画面

Spa*_*ena 2 performance android android-layout android-studio

我正在使用AppCompatDelegate.setDefaultNightMode(mode);在我的 Android 应用程序中设置夜间模式,每当用户在其设备上的共享首选项中选择首选项配置的任何模式时,现在当应用程序从 Splash 启动时,我使用共享首选项来设置 UI 模式屏幕活动,该活动正在重新创建,然后我的应用程序有 2 个实例,因为启动屏幕意图登陆活动。

这是我的 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();
    }
Run Code Online (Sandbox Code Playgroud)

我该如何避免创建登陆活动的多个实例?

l33*_*33t 5

请务必AppCompatDelegate.setDefaultNightMode()尽快致电。例如在打电话之前super.onCreate()。理想情况下,您希望将其调用到Application.onCreate(). 另外,请确保使用最新版本AppCompat(至少 1.1.0),否则您可能会遇到此问题。

有关更多详细信息,请参阅此答案。