使用方向传感器,定位手机y轴方向(y轴与北方夹角0-360度)
y轴: 手机长边方向 x轴:手机短边方向 z轴:与手机平面垂直方向
本文源码:https://github.com/lioilwin/StepOrient
一.使用
public class MainActivity extends AppCompatActivity implements OrientSensor.OrientCallBack{
.........
@Override
public void Orient(float orient
) {
orientText
.setText("方向:" + (int) orient
);
}
@Override
protected void onCreate(Bundle savedInstanceState
) {
super.onCreate(savedInstanceState
);
setContentView(R
.layout
.activity_main
);
orientText
= (TextView
) findViewById(R
.id
.orient_text
);
orientSensor
= new OrientSensor(this, this);
if (!orientSensor
.registerOrient()) {
Toast
.makeText(this, "方向传感器不可用!", Toast
.LENGTH_SHORT
).show();
}
}
.......
}
二.方向传感器类
public class OrientSensor implements SensorEventListener {
private static final String TAG
= "OrientSensor";
private SensorManager sensorManager
;
private OrientCallBack orientCallBack
;
private Context context
;
float[] accelerometerValues
= new float[3];
float[] magneticValues
= new float[3];
public OrientSensor(Context context
, OrientCallBack orientCallBack
) {
this.context
= context
;
this.orientCallBack
= orientCallBack
;
}
public interface OrientCallBack {
void Orient(int orient
);
}
public Boolean
registerOrient() {
Boolean isAvailable
= true;
sensorManager
= (SensorManager
) context
.getSystemService(Context
.SENSOR_SERVICE
);
if (sensorManager
.registerListener(this, sensorManager
.getDefaultSensor(Sensor
.TYPE_ACCELEROMETER
),
SensorManager
.SENSOR_DELAY_GAME
)) {
Log
.i(TAG
, "加速度传感器可用!");
} else {
Log
.i(TAG
, "加速度传感器不可用!");
isAvailable
= false;
}
if (sensorManager
.registerListener(this, sensorManager
.getDefaultSensor(Sensor
.TYPE_MAGNETIC_FIELD
),
SensorManager
.SENSOR_DELAY_GAME
)) {
Log
.i(TAG
, "地磁传感器可用!");
} else {
Log
.i(TAG
, "地磁传感器不可用!");
isAvailable
= false;
}
return isAvailable
;
}
public void unregisterOrient() {
sensorManager
.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event
) {
if (event
.sensor
.getType() == Sensor
.TYPE_ACCELEROMETER
) {
accelerometerValues
= event
.values
.clone();
} else if (event
.sensor
.getType() == Sensor
.TYPE_MAGNETIC_FIELD
) {
magneticValues
= event
.values
.clone();
}
float[] R
= new float[9];
float[] values
= new float[3];
SensorManager
.getRotationMatrix(R
, null
, accelerometerValues
, magneticValues
);
SensorManager
.getOrientation(R
, values
);
int degree
= (int) Math
.toDegrees(values
[0]);
if (degree
< 0) {
degree
+= 360;
}
orientCallBack
.Orient(degree
);
}
@Override
public void onAccuracyChanged(Sensor sensor
, int accuracy
) {
}
}
简书: http://www.jianshu.com/p/066f667c99c3 博客: http://blog.csdn.net/qq_32115439/article/details/61620059 GitHub博客:http://lioil.win/2017/03/13/Android-Orient.html Coding博客:http://c.lioil.win/2017/03/13/Android-Orient.html
转载请注明原文地址: https://ju.6miu.com/read-34718.html