选择深色模式时应用启动 2 次

App launches 2 times while selecting dark mode

我是在升级项目版本到androidx的时候开始遇到这个错误的。我还升级了所有实现 sdks。我将 min sdk 从 16 升级到 19。在进行这些升级之前,暗模式运行良好。升级后,如果您在选择深色模式的情况下启动应用程序,应用程序会打开 2 次。我该如何解决这个问题?

主要活动;

SwitchCompat nightmodeswitch ;

 if (InıtAplıcation.getInstance().isNightModeEnabled()) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        }

  @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        nightmodeswitch = (SwitchCompat) findViewById(R.id.nightmodeswitch);


        try {
            if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES)
                  nightmodeswitch.setChecked(true);


            nightmodeswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                             InıtAplıcation.getInstance().setIsNightModeEnabled(true);
                            
                           Intent intent = getIntent();
                             intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                           finish();
                           startActivity(intent);

                   

                    } else {
                            InıtAplıcation.getInstance().setIsNightModeEnabled(false);
                            
                            Intent intent = getIntent();
                            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                            finish();
                            startActivity(intent);

                       
                        
                    }


                }
            });
        }catch (Exception e){

        }



        return true;
    }

InıtAplıcation ;

public class InıtAplıcation extends Application {

    public static final String NIGHT_MODE = "NIGHT_MODE";
    private boolean isNightModeEnabled = false;

    private static InıtAplıcation singleton = null;

    public static InıtAplıcation getInstance() {

        if(singleton == null)
        {
            singleton = new InıtAplıcation();
        }
        return singleton;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        FirebaseDatabase.getInstance().setPersistenceEnabled(true);

        singleton = this ;
        SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        this.isNightModeEnabled = mPrefs.getBoolean(NIGHT_MODE, false);
    }

    public boolean isNightModeEnabled() {
        return isNightModeEnabled;
    }

    public void setIsNightModeEnabled(boolean isNightModeEnabled) {
        this.isNightModeEnabled = isNightModeEnabled;

        SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putBoolean(NIGHT_MODE, isNightModeEnabled);
        editor.apply();
    }
}

Values\Styles :

<style name="AppTheme.beyaztema" parent="Theme.AppCompat.Light.NoActionBar" >
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorappaydınlık</item>
        <item name="colorPrimaryDark">#FFF</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

Night\Styles :

  <style name="AppTheme.beyaztema" parent="Theme.AppCompat.Light.NoActionBar" >
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">#000</item>
        <item name="colorPrimaryDark">#000</item>
        <item name="colorAccent">#D81B60</item>
    </style>

Android 清单:

 <application
        android:name=".InıtAplıcation"
        android:allowBackup="true"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.beyaztema">

gradle:

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'



android {
    compileSdkVersion 30
    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 30
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    testImplementation 'junit:junit:4.13.2'
    implementation "androidx.cardview:cardview:1.0.0"
    implementation "androidx.recyclerview:recyclerview:1.2.1"
    implementation "androidx.recyclerview:recyclerview-selection:1.1.0"
    implementation 'com.github.orangegangsters:swipy:1.2.3@aar'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation "androidx.multidex:multidex:2.0.1"
    implementation 'com.google.android.gms:play-services-ads:15.0.1'
    implementation('com.google.apis:google-api-services-people:v1-rev2-1.21.0')
            {
                exclude module: 'guava-jdk5'
            }

    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation "io.grpc:grpc-okhttp:1.32.2"

}

apply plugin: 'com.google.gms.google-services'

Gradle:

buildscript {
    
    repositories {
        google()
        jcenter()

    }
    dependencies {

          classpath 'com.android.tools.build:gradle:7.1.2'
           classpath 'com.google.gms:google-services:4.3.10'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.5.2'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

您实际上 activity 开始了两次。 第一次手动重新创建 activity 和 AppCompatDelegate.setDefaultNightMode 它也会重新创建 activity 以设置默认主题

这就是为什么看起来 activity 被创建了两次。

为此我所做的是在应用程序中应用主题class。 并且没有创建 activity 只是应用了主题

在我的申请中Class

 if (preferencesValue!!.getBoolean("theme")) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
        }

在 activity 中更改主题时对 Switch Button

的更改侦听器执行相同的操作

在您创建意图并开始 activity 的地方,您只需使用 AppCompatDelegate.setDefaultNightMode 设置主题。不要再创建 Activity。

android:configChanges设置为您的activity,它会在选择深色模式后重新启动

        android:configChanges="...|...|...|...|uiMode|...|..."

uiMode 配置处理深色模式 UI 您应用的更改。

参考这个documentation

清单中 activity 的示例

            <activity
            android:name=".SplashActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:launchMode="singleTop"
            android:screenOrientation="sensorLandscape" />

只需删除 Intent 代码,因为默认情况下在 SwitchClick 系统上 recreate 您的应用程序无需手动调用 recreate。您的新代码如下

nightmodeswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                             InıtAplıcation.getInstance().setIsNightModeEnabled(true);
//or
// AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);

                    } else {
                            InıtAplıcation.getInstance().setIsNightModeEnabled(false); 
//or
//AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    }

并编写 SharedPrefrence 代码来保存你当前 boolean 的 DayNight Switch。如果问题还没有解决,请告诉我