安卓罗盘指南针
方式1目前谷歌建议使用SensorManager中Sensor.TYPE_ACCELEROMETER和Sensor.TYPE_MAGNETIC_FIELD
SensorManager sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);//获取传感器管理
Sensor aSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);//加速度传感器
Sensor mSensor = sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);//磁力传感器
sm.registerListener(mOrientationSensorEventListener, aSensor,SensorManager.SENSOR_DELAY_UI);//注册传感器监听器
sm.registerListener(mOrientationSensorEventListener, mSensor,SensorManager.SENSOR_DELAY_UI);
private float[] accelerometerValues = new float[3];
private float[] magneticFieldValues = new float[3];
private float[] values = new float[3];
private float[] rotate = new float[9];
private final SensorEventListener mOrientationSensorEventListener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
accelerometerValues = event.values;
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magneticFieldValues = event.values;
}
SensorManager.getRotationMatrix(rotate, null, accelerometerValues,magneticFieldValues);//通过磁力和加速度值计算旋转矩阵,赋值给rotate
SensorManager.getOrientation(rotate, values);//最后通过矩阵数组计算x,y,z方向手机角度,目前我们需要第一个角度x轴的
values[0] = (float) Math.toDegrees(values[0]);
Log.i("test","定位角度是:"+values[0]);//此结果为从北到南顺时针为0-180度,从南-北顺指针-180到0度,其实是弧度运算的,也就是从北顺指针是0-360度
}
};
方式2 已经不建议使用的SensorManager中Sensor.TYPE_ORIENTATION
SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor mOrientationSensor = mSensorManager.getSensorList(Sensor.TYPE_ORIENTATION).get(0);//获取方向传感器
if (mOrientationSensor != null) {
mSensorManager.registerListener(mOrientationSensorEventListener,mOrientationSensor,SensorManager.SENSOR_DELAY_GAME);//注册方向传感器监听器
}
// 方向传感器变化监听
private SensorEventListener mOrientationSensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float direction = event.values[mSensorManager.DATA_X]
// Log.i("way", "角度:"+direction);//此角度值为从北顺时针0-360
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};