保存开关状态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");
    }
}
}

您可以使用共享preferences进行相同的使用,当发生交换机检查事件时,只需将其值保存到true else else设置false。https://developer.android.com/guide/topics/data/data-storage.html#pref

在活动中,只需检查fro sharedPrefernce值,如果它是true set switch on else set of of sele of

on Create检查开关值

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

保存状态的代码在开关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();
        }

最新更新