当我运行我的代码时,加速度计返回的值似乎是随机的,即使我拿起设备并旋转它,值似乎也没有任何显着变化或设备已经改变的明显迹象从静止位置到移动位置。我从谷歌的网站上复制了代码。基本上我想看看设备是否已经从静止位置移动了。如果可能,解决方案应该适用于 Android 2.2 及更高版本:
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST);
float[] gravity = new float[3];
@Override
public void onSensorChanged(SensorEvent event)
{
try
{
final float alpha = 0.8f;
float[] linear_acceleration = new float[3];
// Isolate the force of gravity with the low-pass filter.
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];
// Remove the gravity contribution with the high-pass filter.
linear_acceleration[0] = event.values[0] - gravity[0];
linear_acceleration[1] = event.values[1] - gravity[1];
linear_acceleration[2] = event.values[2] - gravity[2];
}
catch (Exception ex)
{
}
}