简体   繁体   中英

how to save the state of switch(button) in android

I am using switch (like android togglebutton ) instead of normal buttons in my android app. The code works fine while enabling and disabling switches. But i want to store the state of the switch. Suppose i enable the switch and close my application the background code will run fine but the switch state will change to disabled.

Every time when i close the application the switch state becomes disabled. Is there any way to store the switch State?

mySwitch.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
    if (mySwitch.isChecked()) {
        SharedPreferences.Editor editor = getSharedPreferences ("com.mobileapp.smartapplocker",
        MODE_PRIVATE).edit();
        editor.putBoolean("Service On", true);
        editor.commit();
    }

    else {
        SharedPreferences.Editor editor = getSharedPreferences ("com.mobileapp.smartapplocker",
        MODE_PRIVATE).edit();
        editor.putBoolean("Service Off", false);
        editor.commit();
    }
  }
}

I think you are confused on how shared preferences work in android. They are basically key value pairs. So in order to retrieve a particular value, the key has to be same.

Giving you an example below:

    mySwitch.setOnClickListener(new View.OnClickListener() {

       @Override
       public void onClick(View arg0) {    
           SharedPreferences.Editor editor = getSharedPreferences("com.mobileapp.smartapplocker", MODE_PRIVATE).edit();
           editor.putBoolean("service_status", mySwitch.isChecked());
           editor.commit();
       }
   }

Now where ever you are check for service

  SharedPreferences prefs = getSharedPreferences("com.mobileapp.smartapplocker", MODE_PRIVATE);
  boolean switchState = pref.getBoolean("service_status", false);

  if(switchState){
        //Do your work for service is selected on
  } else {
        //Code for service off
  }

Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM