我之前正在研究开源地图项目,如OsmAnd,MapsWithMe和MapBox.我认为这些项目是地图和导航领域中最好的Android开源.我检查了他们的代码,发现当手机垂直然后围绕垂直轴(y)旋转时,显示罗盘的MapBox方法是稳定的.如果旋转矢量传感器可用,它使用TYPE_ROTATION_VECTOR.否则,它使用TYPE_ORIENTATION传感器或TYPE_ACCELEROMETER和TYPE_MAGNETIC_FIELD的组合.在使用TYPE_ACCELEROMETER和TYPE_MAGNETIC_FIELD的情况下,可以通过低通滤波器减少结果的振荡,以实现更平滑的值.
这是MapBox的指南针引擎及其用法.
.
LocationComponentCompassEngine.java:
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Surface;
import android.view.WindowManager;
import timber.log.Timber;
import java.util.ArrayList;
import java.util.List;
/**
* This manager class handles compass events such as starting the tracking of device bearing,or
* when a new compass update occurs.
*/
public class LocationComponentCompassEngine implements SensorEventListener {
// The rate sensor events will be delivered at. As the Android documentation states,this is only
// a hint to the system and the events might actually be received faster or slower then this
// specified rate. Since the minimum Android API levels about 9,we are able to set this value
// ourselves rather than using one of the provided constants which deliver updates too quickly for
// our use case. The default is set to 100ms
private static final int SENSOR_DELAY_MICROS = 100 * 1000;
// Filtering coefficient 0 < ALPHA < 1
private static final float ALPHA = 0.45f;
// Controls the compass update rate in milliseconds
private static final int COMPASS_UPDATE_RATE_MS = 500;
private final WindowManager windowManager;
private final SensorManager sensorManager;
private