------------------------------------------------------------------------------------------
package com.pocketdigi;
import com.pocketdigi.ShakeListener.OnShakeListener;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class SensorTestActivity extends Activity {
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ShakeListener shakeListener = newShakeListener(this); // 创建一个对象
shakeListener.setOnShakeListener(newOnShakeListener() { // 调用setOnShakeListener方法进行监听
public void onShake() {
// 对手机摇晃后的处理(如换歌曲,换图片……)
Log.e("", "onShake");
}
});
}
}

----------------------------------------------------------------------
package com.pocketdigi;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class ShakeListener implements SensorEventListener {
//速度阈值,当摇晃速度达到这值后产生作用
privatestatic final int SPEED_SHRESHOLD = 4000;
//两次检测的时间间隔
privatestatic final int UPTATE_INTERVAL_TIME = 70;
//传感器管理器
privateSensorManager sensorManager;
// 传感器
privateSensor sensor;
//重力感应监听器
privateOnShakeListener onShakeListener;
// 上下文
privateContext context;
//手机上一个位置时重力感应坐标
privatefloat lastX;
privatefloat lastY;
privatefloat lastZ;
//上次检测时间
private longlastUpdateTime;
// 构造器
publicShakeListener(Context c) {
//获得监听对象
context =c;
start();
}
// 开始
public voidstart() {
//获得传感器管理器
sensorManager = (SensorManager) context
.getSystemService(Context.SENSOR_SERVICE);
if(sensorManager != null) {
//获得重力传感器
sensor =sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
// 注册
if (sensor!= null) {
sensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_GAME);
}
}
//停止检测
public voidstop() {
sensorManager.unregisterListener(this);
}
//摇晃监听接口
publicinterface OnShakeListener {
public voidonShake();
}
//设置重力感应监听器
public voidsetOnShakeListener(OnShakeListener listener) {
onShakeListener = listener;
}
//重力感应器感应获得变化数据
public voidonSensorChanged(SensorEvent event) {
//现在检测时间
longcurrentUpdateTime = System.currentTimeMillis();
//两次检测的时间间隔
longtimeInterval = currentUpdateTime - lastUpdateTime;
//判断是否达到了检测时间间隔
if(timeInterval < UPTATE_INTERVAL_TIME)
return;
//现在的时间变成last时间
lastUpdateTime = currentUpdateTime;
//获得x,y,z坐标
float x =event.values[0];
float y =event.values[1];
float z =event.values[2];
//获得x,y,z的变化值
float deltaX= x - lastX;
float deltaY= y - lastY;
float deltaZ= z - lastZ;
//将现在的坐标变成last坐标
lastX =x;
lastY =y;
lastZ =z;
double speed= Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ
*deltaZ)
/timeInterval * 10000;
//达到速度阀值,发出提示
if (speed>= SPEED_SHRESHOLD)
onShakeListener.onShake();
}
public voidonAccuracyChanged(Sensor sensor, int accuracy) {
}
}