与传感器事件检测手机方向
问题描述:
我有一个活动,需要它的方向要与与传感器事件检测手机方向
setRequestedOrientation(screenOrientation);
锁定,但我想的方向更新,这样我就可以做调整,UI(想象一下HTC相机应用程序,当只有按钮的图标改变方向时)。 所以我找到了this class。它提供的方向值介于0和360之间。我是否要过滤这个值,即完美区间[a, b]
,如果a<x<b
那么方向是横向还是纵向?计算是什么意思?任何提示?
答
听起来好像你需要的代码只有当设备的方向改变为4个正常方向之一而不是每个角度时才会有反应。这将定向筛选为0,90,180和270度只值:
OrientationEventListener myOrientationEventListener;
int iOrientation;
myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL)
{
@Override
public void onOrientationChanged(int iAngle)
{ // 0 15 30 45 60 75, 90 105, 120, 135, 150, 165, 180, 195, 210, 225, 240, 255, 270, 285, 300, 315, 330, 345
final int iLookup[] = {0, 0, 0,90,90, 90,90, 90, 90, 180, 180, 180, 180, 180, 180, 270, 270, 270, 270, 270, 270, 0, 0, 0}; // 15-degree increments
if (iAngle != ORIENTATION_UNKNOWN)
{
int iNewOrientation = iLookup[iAngle/15];
if (iOrientation != iNewOrientation)
{
iOrientation = iNewOrientation;
// take action on new orientation here
}
}
}
};
// To display if orientation detection will work and enable it
if (myOrientationEventListener.canDetectOrientation())
{
Toast.makeText(this, "Can DetectOrientation", Toast.LENGTH_LONG).show();
myOrientationEventListener.enable();
}
else
{
Toast.makeText(this, "Can't DetectOrientation", Toast.LENGTH_LONG).show();
}
我不得不改变查找值有点为它与我的硬件正常工作,但这个效果很好。我希望有一个更好的方式来做到这一点,但在那之前它正在做它的工作。谢谢! – nrflaw 2014-01-05 14:05:24
谁曾发布这是一个G!我在getResources()。getConfiguration()。orientation中没有任何帮助的时候遇到了这个问题 – Matt 2014-09-05 19:47:36