I have successfully created a button that mute my button press sound if wanted. The problem I am having is that when I leave the page or close the app and return sound a returne
In your OnClickListener's onClick method you can save the state
getSharedPreferences("SP", Context.MODE_PRIVATE).edit().putBoolean("mute_pressed", true).commit();
or if you want to save the int value like you are in onPause just do
getSharedPreferences("SP", Context.MODE_PRIVATE).edit().putBoolean("mute_val", Sound).commit();
Because as of right now you aren't actually saving as you increment/decrement you are only saving onPause(). You can then restore that value in onResume() by changing
int counter = ...
// to
Sound =...
This will set your classes Sound variable to the old stored value.
I would also recommend, instead of using "SP"
(I highly recommend against using the same key values for your shared preference key and your stored value key while I am at it), to use static variables you set in the top of your class as something like
private final static String PREFS_KEY = "shared_prefs";
then use your variables like
getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)...
this helps with localization. You should also check into naming conventions in Java to avoid headaches down the road when things get more complicating.
UPDATED TO WORK WITH YOUR CODE
// this should be HomePage, not homePage
public class homePage extends Activity {
private final static String PREFS_KEY = "shared_prefs";
private final static String MUTE_PRESSED_KEY = "mute_pressed";
private Button Mute; // this should be mute, not Mute
private int Sound = 0; // this should be sound, not Sound
private SharedPreferences prefs;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_page);
Mute = (Button) findViewById(R.id.mute);
setButtonOnClickListeners();
prefs = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
if(prefs.getBoolean(MUTE_PRESSED_KEY, false))
Sound = 1;
else
Sound = 0;
}
// I DIDN'T REALLY LOOK AT THIS SO COUNTING ON YOU THAT IT WORKS
public void sound() {
final MediaPlayer mp = new MediaPlayer();
if (Sound == 1) {
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("butpress.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if (Sound == 0) {
mp.stop();
}
}
private void setButtonOnClickListeners() {
Mute.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (Sound == 1) {
Mute.setBackgroundResource(R.drawable.sound_off);
Sound = 0;
prefs.edit().putBoolean(MUTE_PRESSED_KEY, false).commit();
} else if (Sound == 0) {
Mute.setBackgroundResource(R.drawable.sound_high);
Sound = 1;
prefs.edit().putBoolean(MUTE_PRESSED_KEY, true).commit();
}
}
});
}
}