使用传感器事件检测手机方向

7

我有一个Activity,需要锁定其方向

setRequestedOrientation(screenOrientation);

但我想获取方向更新,以便我可以对UI进行调整(想象一下HTC相机应用程序,当仅按钮图标更改方向时)。因此,我找到了这个类。它提供了0到360之间的方向值。如何过滤这些值,即找到完美的区间[a, b],并且如果a<x<b,则方向为横向或纵向?计算平均值?有任何提示吗?
1个回答

7

听起来您需要的代码只在设备方向改变为四个正常方向之一时才作出反应,而不是每个角度都作出反应。这将过滤方向,仅保留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
1
发帖者太牛了!我被这个问题困扰了一段时间,但是getResources().getConfiguration().orientation没有提供任何帮助。 - Matt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接