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

标签 android

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

setRequestedOrientation(screenOrientation);

但我想获得方向更新,以便我可以对 UI 进行调整(想象一下 HTC 相机应用程序,当只有按钮的图标改变方向时)。 所以我找到了this class .它提供 0 到 360 之间的方向值。我如何过滤这些值,即完美间隔 [a, b] , 如果 a<x<b那么方向是横向还是纵向?计算的意思?有什么提示吗?

最佳答案

听起来您需要代码仅在设备方向更改为 4 个正常方向之一而不是每个角度时才使用react。这会将方向过滤为仅值 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();
    }

关于android - 使用传感器事件检测手机方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9295127/

相关文章:

android - 单击按钮动画并使用其他动画转到其他 Activity

java - Android Parcelable Class - 内部类不能有静态声明

java - 关于 Android 开发 IDE 和框架

android - 多色边框EditText

android - 放大身份验证 (Cognito) - 登录期间的 "Error in federating the token"

java - 按照拍摄图像的顺序从图库加载图像?

java - 如何在 GWT 中通过 Property Provider 获取 Android 版本?

android - 以编程方式将 EditText 的输入类型从 PASSWORD 更改为 NORMAL,反之亦然

java.lang.RuntimeException : Unable to start activity ComponentInfo when using admob sdk

android - 创建项目菜单中 API 集成的 Eclipse 插件和 ADT 修改