保存开关状态android

时间:2017-05-01 19:47:31

标签: android

您好我不知道如何让我的应用保存开关状态
例如:
我想打开应用程序,我想在重启我的应用程序后关闭交换机我希望我的应用程序保持状态关闭,反之亦然

public class AlgeriaNotificationsActivity extends AppCompatActivity {

public static final String PREFS_NAME = "MyPrefsFile";
private TextView switchStatus;
private Switch mySwitch;

private static final String TAG = "AlgeriaNotificationsActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_algeria_notifications);

    switchStatus = (TextView) findViewById(R.id.switchStatus);
    mySwitch = (Switch) findViewById(R.id.mySwitch);

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    boolean silent = settings.getBoolean("switchkey", false);
    mySwitch.setChecked(silent);

    mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                                     boolean isChecked) {

            if(isChecked){
                switchStatus.setText("Switch is currently ON");
            }else{
                switchStatus.setText("Switch is currently OFF");
            }
            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putBoolean("switchkey", isChecked);
        }
    });

    //check the current state before we display the screen
    if(mySwitch.isChecked()){
        switchStatus.setText("Switch is currently ON");
    }
    else {
        switchStatus.setText("Switch is currently OFF");
    }
}

}

1 个答案:

答案 0 :(得分:1)

您可以使用SharedPreferences,当切换检查事件发生时,只需将其值保存为true,否则设置为false。 https://developer.android.com/guide/topics/data/data-storage.html#pref

在活动oncreate中只检查sharedprefernce值,如果是真的设置开关打开,否则

oncreate check for switch value

 SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   boolean silent = settings.getBoolean("switchkey", false);
   mySwitch.setChecked(silent);

switch checkchange中保存状态的代码

 @Override
        public void onCheckedChanged(CompoundButton buttonView,
                                     boolean isChecked) {

            if(isChecked){
                switchStatus.setText("Switch is currently ON");
            }else{
                switchStatus.setText("Switch is currently OFF");
            }
 SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("switchkey", isChecked);
 editor.commit();
        }