使用下面的类作为摇动监听器,
import java.util.List;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class ShakeListener implements SensorEventListener{
private MyShakeListener mOnShakeListener = null;
private SensorManager mSensorManager;
private double mTotalForcePrev;
private double mForceThreshHold = 1.5f;
private List<Sensor> mSensors;
private Sensor mAccelerationSensor;
public ShakeListener(SensorManager sm){
mSensorManager = sm;
mSensors = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(mSensors.size() > 0) {
mAccelerationSensor = mSensors.get(0);
mSensorManager.registerListener(this, mAccelerationSensor, SensorManager.SENSOR_DELAY_GAME);
}
}
public void setForceThreshHold(double threshhold){
mForceThreshHold = threshhold;
}
public double getForceThreshHold(){
return mForceThreshHold;
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
double totalForce = 0.0f;
totalForce += Math.pow(event.values[0]/SensorManager.GRAVITY_EARTH, 2.0);
totalForce += Math.pow(event.values[1]/SensorManager.GRAVITY_EARTH, 2.0);
totalForce += Math.pow(event.values[2]/SensorManager.GRAVITY_EARTH, 2.0);
totalForce = Math.sqrt(totalForce);
if((totalForce < mForceThreshHold) && (mTotalForcePrev > mForceThreshHold)) {
OnShake();
}
mTotalForcePrev = totalForce;
}
public void setOnShakeListener(MyShakeListener listener)
{
mOnShakeListener = listener;
}
private void OnShake()
{
if(mOnShakeListener!=null)
{
mOnShakeListener.onShake();
}
}
}
public interface MyShakeListener {
public abstract void onShake();
}
并像这样在你的主类上添加 lisener 类,
public class MainActivity extends Activity
{
MediaPlayer defaultPlayer;
@Override
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.playerscree);
ShakeListener myShake = new ShakeListener((SensorManager)getSystemService(Context.SENSOR_SERVICE));
myShake.setForceThreshHold(1.9);
myShake.setOnShakeListener(new MyShakeListener()
{
@Override
public void onShake()
{
// do ur work here...
defaultPlayer= MediaPlayer.create(getApplicationContext(), R.raw.music);
defaultPlayer.start();
}
});
}