当我调试下面发布的代码时,我决定在Toast
语句的正文和if
语句的正文中放置else
,所以我可以看到错误来自哪里。当我运行应用程序时,我发现两个Toasts
都已执行。最初显示Toast
语句中的if
,并且在几秒钟后,显示切换到Toast
语句中的else
,并且它们保持交替。我不知道条件如何被评估为真和假同时。请提供解决此问题的合理解释和建议。
JavaCode:
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
accelerometerValues = event.values.clone();
tvAcc_XReading.setText(Float.toString(accelerometerValues[0]));
tvAcc_YReading.setText(Float.toString(accelerometerValues[1]));
tvAcc_ZReading.setText(Float.toString(accelerometerValues[2]));
case Sensor.TYPE_MAGNETIC_FIELD:
magnetometerValues = event.values.clone();
tvMagneto_XReading.setText(Float.toString(magnetometerValues[0]));
tvMagneto_YReading.setText(Float.toString(magnetometerValues[1]));
tvMagneto_ZReading.setText(Float.toString(magnetometerValues[2]));
}
if (accelerometerValues != null && magnetometerValues != null) {
float [] matrixR = new float[9];
float [] matrixI = new float[9];
boolean success = SensorManager.getRotationMatrix(matrixR, matrixI, accelerometerValues,
magnetometerValues);
if (success) {
Toast.makeText(getApplicationContext(), "SUCCESS", Toast.LENGTH_LONG).show();
float [] orientationMatrix = new float[3];
SensorManager.getOrientation(matrixR, orientationMatrix);
tvAzimuthReading.setText(Float.toString(orientationMatrix[0]));
tvPitchReading.setText(Float.toString(orientationMatrix[1]));
tvRollReading.setText(Float.toString(orientationMatrix[2]));
} else {
Toast.makeText(getApplicationContext(), "No Rmatrix", Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:0)
尝试为您的案例添加一个break语句,否则它会失败。
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
accelerometerValues = event.values.clone();
tvAcc_XReading.setText(Float.toString(accelerometerValues[0]));
tvAcc_YReading.setText(Float.toString(accelerometerValues[1]));
tvAcc_ZReading.setText(Float.toString(accelerometerValues[2]));
break;
case Sensor.TYPE_MAGNETIC_FIELD:
magnetometerValues = event.values.clone();
tvMagneto_XReading.setText(Float.toString(magnetometerValues[0]));
tvMagneto_YReading.setText(Float.toString(magnetometerValues[1]));
tvMagneto_ZReading.setText(Float.toString(magnetometerValues[2]));
break;
}