如何获得Android设备的物理方向度。

时间:2014-03-17 13:46:01

标签: android

我知道我必须使用OrientationListener类来获取设备的角度。我想获得-90°和90°之间的角度。我不知道怎么做。 左边的图片:90度,中间的图片:0度,右边的图片:-90度

90 degree 0 degree -90 degree

代码

class OrientationListener implements SensorEventListener
{

    @Override
    public void onSensorChanged(SensorEvent event)
    {
        angle = Math.round(event.values[2]);

        if (angle < 0)
        {
            angle = angle * -1;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy)
    {
    }
}

3 个答案:

答案 0 :(得分:1)

您可以将此代码用于简单的0,90,180度。

Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

int rotation = display.getRotation();

Surface.ROTATION_0为0度,Surface,ROTATION_90为90度等。

如果你想要0,90等以外的度数,你也可以使用SensorEventListener接口:

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

        float rawX = event.values[0];
    }
}

您需要使用此代码获取学位:

double k = 90/9.8;
double degrees = rawX * k; // this is a rough estimate of degrees, converted from gravity

答案 1 :(得分:1)

这是一个有效的例子。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView tv = new TextView(this);
    setContentView(tv);

    Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
    int rotation = display.getRotation();

    String rotString="";
    switch(rotation) {
    case Surface.ROTATION_0:
        rotString="portrait";
        break;
    case Surface.ROTATION_90:
        rotString="landscape left";
        break;
    case Surface.ROTATION_180:
        rotString="flipped portrait";
        break;
    case Surface.ROTATION_270:
        rotString="landscape right";
        break;
    }

    tv.setText(rotString);

}

答案 2 :(得分:1)

这是一个老问题,但我在尝试以度数计算rotation for a camera时找到了一个OrientationEventListener()。

 public void onOrientationChanged(int orientation) {
     if (orientation == ORIENTATION_UNKNOWN) return;
     android.hardware.Camera.CameraInfo info =
            new android.hardware.Camera.CameraInfo();
     android.hardware.Camera.getCameraInfo(cameraId, info);
     orientation = (orientation + 45) / 90 * 90;
     int rotation = 0;
     if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
         rotation = (info.orientation - orientation + 360) % 360;
     } else {  // back-facing camera
         rotation = (info.orientation + orientation) % 360;
     }
     mParameters.setRotation(rotation);
 }

这里的答案实际上对我有帮助,因为我没有捕获开发者指南中Handling Runtime Changes Yourself主题中讨论的onConfigurationChanged()

我只是在MyActivity的display.getRotation()中使用Elduderino提供的onSurfaceCreated()方法来适当地设置相机的旋转。这将在设备方向更改时默认情况下重新创建曲面时起作用。