What I'm trying to do is if the user shakes the phone nothing happens. If then the user presses the button and shaking the phone plays a sound. When the user presses the button again the sound stops. This works the first time, but if the user does the same thing again can't the user stop the sound with a second click. The sound never stops.
locked = true / false, just to check if the button is pressed previously running = true / false, is to see if a sound is already playing and if so, do not start a new audio playback
Detect shaking using this code
Make Sound using this code
And this is my code with a button:
/* The SensorEventListener lets us wire up to the real hardware events */
private final SensorEventListener mySensorEventListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent se) {
updateAccelParameters(se.values[0], se.values[1], se.values[2]); // (1)
if ((!shakeInitiated) && isAccelerationChanged()) { // (2)
shakeInitiated = true;
} else if ((shakeInitiated) && isAccelerationChanged()
&& locked == true && running == false) { // (3)
running = true;
executeShakeAction();
} else if ((shakeInitiated) && (!isAccelerationChanged())) { // (4)
shakeInitiated = false;
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
/* can be ignored in this example */
}
};
ImageButton.OnClickListener UnlockedButtonOnClickListener = new ImageButton.OnClickListener() {
@Override
public void onClick(View v) {
//Locking
if(locked == false){
unlocked.setImageResource(R.drawable.pink_locked);
SoundManager.playSound(1, 1);
locked = true;
}else {
//Unlocking
SoundManager.stopSound(2); //stop the sound, working first time
unlocked.setImageResource(R.drawable.blue_unlocked);
SoundManager.playSound(3, 1);
locked = false;
running = false;
}
}
};