一、简介
二、代码
1.java
(1)MainActivity.java
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle; public class MainActivity extends Activity {
/** Called when the activity is first created. */ private SensorManager sensorManager;
private Sensor accelerometerSensor;
private float gravity [] = new float[3];
private float linear_acceleration [] = new float[3];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(new SensorEventListener() { public void onSensorChanged(SensorEvent event) { /*System.out.println("x---" + event.values[0]);
System.out.println("y---" + event.values[1]);
System.out.println("z---" + event.values[2]);*/
final float alpha = 0.8f; //用滤波器过滤掉杂质
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]; 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(linear_acceleration[0]);
System.out.println(linear_acceleration[1]);
System.out.println(linear_acceleration[2]);
// System.out.println(gravity[0]);
// System.out.println(gravity[1]);
// System.out.println(gravity[2]);
} public void onAccuracyChanged(Sensor sensor, int accuracy) { }
}, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}