Android 获取加速传感器的值,并去除杂音
1、注册和注销传感器
private void registerSensor() { manager.registerListener(this, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); manager.registerListener(this, manager.getDefaultSensor(Sensor.TYPE_GRAVITY), SensorManager.SENSOR_DELAY_NORMAL); } private void unregisterSensor() { manager.unregisterListener(this); }
2、执行注册和注销
@Override protected void onResume() { super.onResume(); registerSensor(); } @Override protected void onPause() { super.onPause(); unregisterSensor(); }
3、实现SensorEventListener,获取加速传感器的值,并去除杂音
@Override public void onSensorChanged(SensorEvent event) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: float[] values = event.values; gravityValues[0] = gravityValues[0] * alpha + (1 - alpha) * values[0]; gravityValues[1] = gravityValues[1] * alpha + (1 - alpha) * values[1]; gravityValues[2] = gravityValues[2] * alpha + (1 - alpha) * values[2]; String strAccelerometer = String.format(Locale.CHINA, ">>>>>>>>Accelerometer X:%f, Y:%f, Z:%f", event.values[0] - gravityValues[0], event.values[1] - gravityValues[1], event.values[2] - gravityValues[2]); System.out.println(strAccelerometer); break; case Sensor.TYPE_GRAVITY: gravityValues[0] = event.values[0]; gravityValues[1] = event.values[1]; gravityValues[2] = event.values[2]; break; default: break; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub }