【发布时间】:2014-05-28 06:56:53
【问题描述】:
我目前正在研究有关测量我的 Android 设备的方向角度的运动传感器。在实现方面,无论我们如何转动,设备都会归零。是否有任何条件来初始化浮点数组以便可以计算角度?
下面是我的代码
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
TextView xCoor; // declare X axis object
TextView yCoor; // declare Y axis object
TextView zCoor; // declare Z axis object
float[] mRotationMatrixFromVector = new float[3];
float[] mRotationMatrix = new float[9];
float[] orientationVals = new float[3];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xCoor=(TextView)findViewById(R.id.xcoor); // create X axis object
yCoor=(TextView)findViewById(R.id.ycoor); // create Y axis object
zCoor=(TextView)findViewById(R.id.zcoor); // create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
// add listener. The listener will be HelloAndroid (this) class
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
// check sensor type
if(event.sensor.getType()==Sensor.TYPE_ROTATION_VECTOR){
SensorManager.getRotationMatrixFromVector(mRotationMatrixFromVector, event.values);
SensorManager.remapCoordinateSystem(mRotationMatrixFromVector,
SensorManager.AXIS_X, SensorManager.AXIS_Z,
mRotationMatrix);
SensorManager.getOrientation(mRotationMatrix, orientationVals);
// Optionally convert the result from radians to degrees
orientationVals[0] = (float) Math.toDegrees(orientationVals[0]);
orientationVals[1] = (float) Math.toDegrees(orientationVals[1]);
orientationVals[2] = (float) Math.toDegrees(orientationVals[2]);
xCoor.setText("X: "+ String.valueOf(orientationVals[0]));
yCoor.setText("Y: "+ String.valueOf(orientationVals[1]));
zCoor.setText("Z: "+ String.valueOf(orientationVals[2]));
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
【问题讨论】: