试试这个: 首先实现SensorEventListener并获得RotationSensor
sensorManager = (SensorManager)getActivity().getSystemService(Context.SENSOR_SERVICE);
rotationSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
sensorManager.registerListener(this, rotationSensor, SENSOR_INTERVAL);
int FROM_RADS_TO_DEGS = -57;
然后你就可以检测设备的这样的角度:
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor == rotationSensor) {
if (event.values.length > 4) {
float[] truncatedRotationVector = new float[4];
System.arraycopy(event.values, 0, truncatedRotationVector, 0, 4);
updateRotation(truncatedRotationVector);
} else {
updateRotation(event.values);
}
}
}
private void updateRotation(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;
if(pitch < -45 && pitch > -135) {
// if device is laid flat on a surface, we don't want to change the orientation
return;
}
float roll = Math.abs(orientation[2] * FROM_RADS_TO_DEGS);
if((roll > 45 && roll < 135)) {
// The device is closer to landscape orientation. Enable fullscreen
if(!player.isFullScreen()) {
if(getActivity() != null) {
player.setFullScreenOn();
}
}
}
else {
// The device is closer to portrait orientation. Disable fullscreen
if(player.isFullScreen()) {
if(getActivity() != null) {
player.setFullScreenOff();
}
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do nothing
}
这引起了原代码的教程,但不久前,所以我不记得教程的位置。该版本根据我的要求进行了大量定制,但如果有人从原始版本中识别出来,请将其放入链接中。
我使用此代码来检测视频播放器何时应该全屏内的ViewPage,我不想让横向方向上。除了一件事情,它运作良好:
它使用RotationSensor硬件,并非所有的Android设备都有RotationSensor。如果有人知道使用一些包含在所有设备上的硬件来做到这一点的方法(肯定有一种方法是因为Android知道何时切换方向),请在评论中告诉我,以便我可以更新自己的代码。