当我摇动手机时,我做了一个播放声音的应用程序。 问题是我不知道如何只播放一次声音, 因为它多次播放声音。
我的项目没有错误。
以下是我的活动代码: 公共类MainActivity扩展了Activity {
private SensorManager mySensorManager;
private float xAccel;
private float yAccel;
private float zAccel;
private float xPreviousAccel;
private float yPreviousAccel;
private float zPreviousAccel;
private boolean firstUpdate = true;
private boolean shakeInitiated = false;
private final float shakeThreshold = 5f;
private final SensorEventListener mySensorEventListener = new SensorEventListener(){
public void onSensorChanged(SensorEvent se){
updateAccelParameters(se.values[0], se.values[1], se.values[2]);
if((!shakeInitiated) && isAccelerationChanged()){
shakeInitiated = true;
} else if ((shakeInitiated) && isAccelerationChanged()){
executeShakeAction();
} else if ((shakeInitiated) && !isAccelerationChanged()){
shakeInitiated = false;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
private void updateAccelParameters(float xNew, float yNew, float zNew){
if (firstUpdate){
xPreviousAccel = xNew;
yPreviousAccel = yNew;
zPreviousAccel = zNew;
firstUpdate = false;
} else {
xPreviousAccel = xAccel;
yPreviousAccel = yAccel;
zPreviousAccel = zAccel;
}
xAccel = xNew;
yAccel = yNew;
zAccel = zNew;
}
private boolean isAccelerationChanged(){
float deltaX = Math.abs(xPreviousAccel - xAccel);
float deltaY = Math.abs(yPreviousAccel - yAccel);
float deltaZ = Math.abs(zPreviousAccel - zAccel);
return (deltaX > shakeThreshold && deltaY > shakeThreshold)
|| (deltaX > shakeThreshold && deltaZ > shakeThreshold)
|| (deltaY > shakeThreshold && deltaZ > shakeThreshold);
}
private void executeShakeAction(){
MediaPlayer player = MediaPlayer.create(this, R.raw.whopa);
Toast.makeText(getApplicationContext(), "Whopa!", Toast.LENGTH_SHORT).show();
player.start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mySensorManager.registerListener(mySensorEventListener,
mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
}