本文由PurpleSword(jzj1993)原创,转载请注明
原文网址 http://blog.csdn.net/jzj1993
1、获取系统服务
private SensorManager sensorManager;
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
2、检测是否有传感器
private boolean checkSensor() {
if (sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) == null) {
return false; // 没有相应传感器
}
}
3、定义传感器监听器
private SensorEventListener sensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// 传感器接收到数据 event.values
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// 传感器精度发生改变 }
};
4、注册传感器监听器
private void startSensor() {
sensorManager.registerListener(sensorListener,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
5、解除注册传感器监听器
private void stopSensor() {
if (sensorManager != null)
sensorManager.unregisterListener(sensorListener);
}