我正试图从手机的陀螺仪中获取数据。 到目前为止,角度不断变化取决于我移动手机的角度。
然而,例如,方位角,我希望它从我开始的位置而不是从北方开始计数 - >我希望它从0开始。
我的问题是:如何保存我从陀螺仪获得的第一个数据,这样当我移动手机时我可以从其余数据中“减去”? 代码如下所示:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
rotationvector=sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
sm.registerListener(this,rotationvector,SensorManager.SENSOR_DELAY_NORMAL);
rotationx=(TextView)findViewById(R.id.rotationx);
rotationy=(TextView)findViewById(R.id.rotationy);
rotationz=(TextView)findViewById(R.id.rotationz);
}
@Override
public void onSensorChanged(SensorEvent event) {
rotationx.setText(" " +event.values[0]);
rotationy.setText(" " +event.values[1]);
rotationz.setText(" " +event.values[2]);
}
我想做的事情就像:
rotationx.setText(" " +event.values[0]-FirstAzimuthValue);
谢谢!
新代码:
private boolean isFirstMeasure = true;
private float FirstAzimuthValue = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
rotationvector=sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
sm.registerListener(this,rotationvector,SensorManager.SENSOR_DELAY_NORMAL);
rotationx=(TextView)findViewById(R.id.rotationx);
rotationy=(TextView)findViewById(R.id.rotationy);
rotationz=(TextView)findViewById(R.id.rotationz);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (isFirstMeasure){
FirstAzimuthValue - event.values[0]; //error this line
isFirstMeasure = false;
}
rotationx.setText(" " +(event.values[0] - FirstAzimuthValue));
rotationy.setText(" " +event.values[1]);
rotationz.setText(" " +event.values[2]);
}
答案 0 :(得分:2)
为什么不
private boolean isFirstMeasure = true;
private float firstAzimuthValue = 0;
// ...
@Override
public void onSensorChanged(SensorEvent event) {
if (isFirstMeasure) {
firstAzimuthValue = event.values[0];
isFirstMeasure = false;
}
rotationx.setText(" " + (event.values[0] - firstAzimuthValue));
rotationy.setText(" " +event.values[1]);
rotationz.setText(" " +event.values[2]);
}