1

在我的名片阅读器应用程序中,我在第一个相机捕捉活动中固定了屏幕方向,现在我想知道方向是横向还是纵向。我使用 SensorManager,但是当移动设备的角度变化很小时,它会提供大部分时间景观。

这里 screenOrientation=0 当横向

当纵向时 screenOrientation=1

private void registerAccelerometerSensor() {
    SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    if (getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_SENSOR_ACCELEROMETER)) {
        eventListener = new SensorEventListener() {

        @Override
            public void onSensorChanged(SensorEvent event) {
                // TODO Auto-generated method stub
                if (event.values[1] < 6.5 && event.values[1] > -6.5) {
                    if (orientation != 1) {
                        Log.d("Sensor", "Landscape");
                        screenOrientation = 0;
                    }

                } else {
                    if (orientation != 0) {
                        Log.d("Sensor", "Portrait");
                        screenOrientation = 1;
                    }
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
                // TODO Auto-generated method stub
            }
        };
        sensorManager.registerListener(eventListener,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_FASTEST);
    } else {
        screenOrientation = -1;
    }
}
4

1 回答 1

1

在此处查看一些示例代码:

public int getScreenOrientation() {
    int rotation = getWindowManager().getDefaultDisplay()
            .getRotation();
    int orientation = getResources().getConfiguration().orientation;

    if (orientation == Configuration.ORIENTATION_PORTRAIT) {
        if (rotation == Surface.ROTATION_0
                || rotation == Surface.ROTATION_270) {
            return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        } else {
            return ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
        }
    }
    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
        if (rotation == Surface.ROTATION_0
                || rotation == Surface.ROTATION_90) {
            return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        } else {
            return ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
        }
    }
    return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
}
于 2013-12-12T06:49:54.903 回答