我需要onSensorChanged(SensorEvent事件)的帮助。当设备面朝下(y轴)0到180时,我可以得到一个Toast消息。但是无法让它在(y轴)-0到-180面朝上的另一个方向上工作。非常感谢任何帮助。
感谢您的关注,
麦克
相关代码如下:
公共类MainActivity扩展Activity实现SensorEventListener {
private SensorManager mSensorManager;
private Sensor mRotationSensor;
private double[] values;
private String TAG;
private static final int SENSOR_DELAY = 500 * 1000; // 500ms
private static final int FROM_RADS_TO_DEGS = -57;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mSensorManager = (SensorManager) getSystemService(Activity.SENSOR_SERVICE);
mRotationSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
mSensorManager.registerListener(this, mRotationSensor, SENSOR_DELAY);
} catch (Exception e) {
Toast.makeText(this, "Hardware compatibility issue", Toast.LENGTH_LONG).show();
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor == mRotationSensor) {
if (event.values.length > 4) {
float[] truncatedRotationVector = new float[4];
System.arraycopy(event.values, 0, truncatedRotationVector, 0, 4);
update(truncatedRotationVector);
} else {
update(event.values);
}
}
}
private void update(float[] vectors) {
float[] rotationMatrix = new float[9];
SensorManager.getRotationMatrixFromVector(rotationMatrix, vectors);
int worldAxisX = SensorManager.AXIS_X;
int worldAxisZ = SensorManager.AXIS_Z;
float[] adjustedRotationMatrix = new float[9];
SensorManager.remapCoordinateSystem(rotationMatrix, worldAxisX, worldAxisZ, adjustedRotationMatrix);
float[] orientation = new float[3];
SensorManager.getOrientation(adjustedRotationMatrix, orientation);
float pitch = orientation[1] * FROM_RADS_TO_DEGS;
float roll = orientation[2] * FROM_RADS_TO_DEGS;
((TextView)findViewById(R.id.pitch)).setText("Pitch: "+pitch);
((TextView)findViewById(R.id.roll)).setText("Roll: "+roll);
if (pitch <= 81 && pitch >= 50) {
// mostly vertical
Toast.makeText(this, "Device Face Down ", Toast.LENGTH_SHORT).show();
}
{
if (pitch < -81&& pitch >= -50) {
Toast.makeText(this, "Device Face Up", Toast.LENGTH_SHORT).show();
}} }