当清单文件中的方向固定为纵向时,如何知道Android OS移动版是横向还是纵向

时间:2013-12-12 05:23:57

标签: android screen sensormanager

在我的名片阅读器应用程序中,我在第一次摄像头捕捉活动中修复了屏幕方向,现在我想知道方向是landScape或肖像。 我使用的是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;
    }
}

1 个答案:

答案 0 :(得分: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;
}