How to keep dark mode enabled even after killing the app?

698 Views Asked by At

This is my code in settings.java class. I have implemented my settings class like this. I want to make dark theme on and after killing the app it has to be present there as well and toggle has to be trued on.

Now I have achieved to make it dark. But when I kill the app and come again it gets disappeared. Toggle is also get turns off.

public class settings extends AppCompatActivity {
    SwitchCompat switchCompat;
    ImageView backbtn;
    Button button;    
    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
            setTheme(R.style.Base_ThemeOverlay_AppCompat_Dark);
        } else {
            setTheme(R.style.Base_Theme_MaterialComponents_Light);
        }
            backbtn = findViewById(R.id.goingback);
        LoadingDialod loadingDialod = new LoadingDialod(settings.this);

        backbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
            }
        });
        switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    loadingDialod.startloadinganimation();

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {                             AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                            Intent intent = new Intent(getApplicationContext(), settings.class);
                            startActivity(intent);
                        }
                    }, 800);

                } else {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

                }
            }
        });
    }
}
2

There are 2 best solutions below

0
On

This answer provides Android's adaptation to dark night mode. The dark theme is suitable for Android 10 (API level 29) and higher. This is a prerequisite.

For API 29 - API 30

If you want to enable dark night mode globally within the app, you need to meet the following conditions:

  1. The corresponding Activity should inherit from AppCompatActivity.

  2. Call the following code at the appropriate place to enable global dark mode in the application.

    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
    

For API 31 and above

If you want to enable dark night mode globally within the app, you need to meet the following conditions:

  1. Get UiModeManager .

    private val uiManager: UiModeManager by lazy {
         getSystemService(UI_MODE_SERVICE) as UiModeManager
    }
    
  2. Call the following code at the appropriate place to enable global dark mode in the application.

    uiManager.setApplicationNightMode(UiModeManager.MODE_NIGHT_YES)
    
0
On

I have already given an answer about this here but I am giving it here also:


  1. Create a class named Preferences Manager

  2. Paste this code in the class

public final SharedPreferences sharedPreferences;

public PreferenceManager(Context context){
    sharedPreferences=context.getSharedPreferences( "PREFS",Context.MODE_PRIVATE );
}
public void putBoolean(String key,Boolean value){
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean( key,value );
    editor.apply();
}
public Boolean getBoolean (String key,Boolean defaultValue){
    return sharedPreferences.getBoolean( key,defaultValue );
}

public void clear(){
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    editor.apply();
}
  1. Then in the fragment make an object named preferences manager like this.

    PreferencesManager preferencesManager = new PreferencesManager(getActivity());

  2. Then add value to it like this

if night mode is set to on.

preferencesManager.putBoolean("NightMode",true);

if night mode is off

preferencesManager.putBoolean("NightMode",false);

and then later to check if night mode if on or off, use this code

if (preferencesManager.getBoolean("NightMode")){
    //night mode is on ,do some magic
}else {
    //night mode is off ,do some magic
}

Edit


Alternatively you can also use my library here to store the data. To store and retrieve, see the README.md file