【问题标题】:how to determine device orientation from the sensors如何从传感器确定设备方向
【发布时间】:2015-09-28 15:05:48
【问题描述】:

我的活动已锁定在 LANDSCAPE 上。但我仍然需要知道设备的方向。所以我选择使用传感器。我有以下代码

sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
...
@Override
  public void onSensorChanged(SensorEvent event) {
    float[] values = event.values;

    // Movement
    float azimuth = values[0];
    float pitch = values[1];
    float roll = values[2];

    if ((-110 <= pitch && pitch <= -70) || (70 <= pitch && pitch <= 110)) {
      //PORTRAIT MODE
      portraitPitch = true;
      landscapePitch = false;
      Log.d(TAG, "portrait mode: pitch = " + pitch);
    } else if ((-20 <= pitch && pitch <= 20) || (-200 <= pitch && pitch <= -160) || (160 <= pitch && pitch <= 200)) {
      //LANDSCAPE MODE
      portraitPitch = false;
      landscapePitch = true;
      Log.d(TAG, "landscape mode : pitch = " + pitch);
    }

    if ((-20 <= roll && roll <= 20)) {
      //PORTRAIT MODE
      portraitRoll = true;
      landscapePitch = false;
      Log.d(TAG, "portrait mode: roll = " + roll);
    } else if ((-110 <= roll && roll <= -70) || (70 <= roll && roll <= 110)) {
      //LANDSCAPE MODE
      portraitRoll = false;
      landscapePitch = true;
      Log.d(TAG, "landscape mode : roll = " + roll);
    }

    if (portraitPitch && portraitRoll && !portrait) {
      portrait = true;
      landscape = false;
      rotateIconsToPortraitMode();
      Log.d(TAG, "portrait mode for icons: pitch = " + pitch + ", roll = " + roll);
    }

    if (landscapePitch && landscapeRoll && !landscape) {
      landscape = true;
      portrait = false;
      rotateIconsToLandscapeMode();
      Log.d(TAG, "landscape mode for icons: pitch = " + pitch + ", roll = " + roll);
    }
}

我的代码运行不可靠,事实上,otateIconsToLandscapeMode() 永远无法到达。

如何使用有关azimuthpitchroll 的信息来确定设备的纵向或横向方向?`我希望我的问题足够具体,可以保证一个具体的答案。谢谢。

【问题讨论】:

标签: android orientation screen-orientation android-sensors android-orientation


【解决方案1】:

oncreate 中实例化一个OrientationEventListener

OrientationEventListener orientationEventListener = new OrientationEventListener(this)
    {
        @Override
        public void onOrientationChanged(int orientation)
        {
            Log.d(TAG, "orientation = " + orientation);
        }
    }; 

    orientationEventListener.enable();

使用方向值可以确定设备是纵向还是横向。

【讨论】:

  • 这正是我需要的..:)
【解决方案2】:

如果您只需要横向与纵向方向,那么间距值就足够了。根据您的具体需求,它可能并不完美。但据我了解,您可以简单地使用音高。因此,您完全按照自己的方式进行操作,只需忽略滚动即可。

【讨论】:

    猜你喜欢
    • 2019-11-01
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多