public class MainActivity extends Activity implements SensorEventListener {
// ...
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// 不需要做处理
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float[] values = event.values;
// 获取x、y、z方向上的加速度值
float x = values[0];
float y = values[1];
float z = values[2];
// 计算加速度大小
float accelerationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
// 如果加速度大小大于2,则认为手机正在上下运动
if (accelerationSquareRoot >= 2) {
// do something
}
}
}
// 在onCreate()中注册SensorEventListener
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
// 在onStop()和onDestroy()中注销SensorEventListener
protected void onStop() {
super.onStop();
// ...
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.unregisterListener(this);
}
protected void onDestroy() {
// ...
}
}