我应该如何使用savePreferences
和loadPreferences
方法在第一个活动中?
private static final String GLOBAL_PREFERENCES = "music_status";
public static void savePreferences(@NonNull Context context, String key, int value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}...
protected void onResume() {
super.onResume();
musicGroup = (RadioGroup) findViewById(R.id.radioGroupForMusic);
turnOn = (RadioButton) findViewById(R.id.radioButtonMusicOn);
turnOff = (RadioButton) findViewById(R.id.radioButtonMusicOff);
musicGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){
case R.id.radioButtonMusicOff:
mediaPlayer.pause();
savePreferences(MainMenuActivity.this,"music_status",0);
case R.id.radioButtonMusicOn:
mediaPlayer.start();
savePreferences(MainMenuActivity.this,"music_status",1);
}
}
});
}
在第二个活动中。
private static final String GLOBAL_PREFERENCES = "music_status";
public static int loadPreferences(@NonNull Context context, String key, int defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
return sharedPreferences.getInt(key, defaultValue);
}
不过我不知道如何从第一个活动中获取值
MainMenuActivity.status
.. 这是一个静态变量吗?注意:建议使用Intents+Extras而不是静态变量。 - OneCricketeer