android 检测屏幕方向,在android中检测屏幕方向

试试这个: 首先实现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知道何时切换方向),请在评论中告诉我,以便我可以更新自己的代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值