Android之传感器(三)加速度
以Nesus s为例,由usb到听筒是Y轴;调节音量到开关屏幕为X轴;屏幕上方向为Z轴。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(new AcceListener(), sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
class AcceListener implements SensorEventListener{
private float gravity[] = new float[3];
private float linear_acceleration[] = new float[3];
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
final float alpha = 0.8f;
//分别算出X,Y,Z重力方向的加速度
gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];
//得到X,Y,Z各个方向的加速度,把重力加速度的影响去掉
linear_acceleration[0] = event.values[0] - gravity[0];
linear_acceleration[1] = event.values[1] - gravity[1];
linear_acceleration[2] = event.values[2] - gravity[2];
System.out.println("x:"+linear_acceleration[0]);
System.out.println("y:"+linear_acceleration[1]);
System.out.println("z:"+linear_acceleration[2]);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}