Iam creating a simple game in android,when l opn app and the sound is starting ,l am want to deactivate the sound with check box, it can deactivate and it shows that music deactivated but the music still on, any help is appreciated.
public class Setting extends Activity {
public static MediaPlayer Sounds;
private CheckBox sound;
private Boolean isChecked = false;
public void Is_checked() {
if (isChecked) {
Sounds.start();
Toast.makeText(Setting.this, "Sound is activated ",
Toast.LENGTH_LONG).show();
}
else {
Sounds.stop();
Toast.makeText(Setting.this, "Sound is deactivated ",
Toast.LENGTH_LONG).show();
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
Sounds = MediaPlayer.create(this, R.raw.backmusic);
isChecked = false;
addListenerOnsound();
}
protected void onStart() {
super.onStart();
isChecked = false;
addListenerOnsound();
}
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.commit();
}
private boolean load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", false);
}
protected void onReStart() {
super.onRestart();
sound.setChecked(load());
}
@Override
void onPause() {
super.onPause();
save(sound.isChecked());
}
@Override
public void onResume() {
super.onResume();
sound.setChecked(load());
}
public void addListenerOnsound() {
sound = (CheckBox) findViewById(R.id.sound);
sound.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
isChecked = true;
Is_checked();
}
if (!((CheckBox) v).isChecked()) {
isChecked = false;
Is_checked();
}} });}}
In case you want to resume the audio you should simply use
Sounds.pause();
instead of
Sounds.stop()
But if you want it to start from the beginning, do this.
public void Is_checked() {
if (isChecked) {
Sounds.start();
Toast.makeText(this, "Sound is activated ",
Toast.LENGTH_LONG).show();
}
else {
Sounds.stop();
Sounds = MediaPlayer.create(this, R.raw.backmusic);
Toast.makeText(this, "Sound is deactivated ",
Toast.LENGTH_LONG).show();
}
}