Search code examples
androidscreen-orientationorientation-changes

Get phone orientation but fix screen orientation to portrait


I want to get the phone orientation but keep the screen orientation to portrait. So no matter the user turns the phone to landscape or portrait, the view stays the same, but I can get whether it is turned to landscape or portrait.

Setting the activity to android:screenOrientation="portrait" will fix both but I wouldn't be able to detect the phone orientation via

public void onConfigurationChanged(Configuration newConfig) {
    switch (newConfig.orientation) {
    case Configuration.ORIENTATION_PORTRAIT:
        Toast.makeText(this, "Portrait", Toast.LENGTH_SHORT).show();
        break;
    case Configuration.ORIENTATION_LANDSCAPE:
        Toast.makeText(this, "Landscape", Toast.LENGTH_SHORT).show();
        break;
    default:
        break;
    }
}

Has anyone an idea how to fix that?


Solution

  • Could you satisfy your requirement with the accelerometer? If so, perhaps something like this (untested) fragment would suit your purposes.

    SensorManager sensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
            sensorManager.registerListener(new SensorEventListener() {
                int orientation=-1;;
    
                @Override
                public void onSensorChanged(SensorEvent event) {
                    if (event.values[1]<6.5 && event.values[1]>-6.5) {
                        if (orientation!=1) {
                            Log.d("Sensor", "Landscape");
                        }
                        orientation=1;
                    } else {
                        if (orientation!=0) {
                            Log.d("Sensor", "Portrait");
                        }
                        orientation=0;
                    }
                }
    
                @Override
                public void onAccuracyChanged(Sensor sensor, int accuracy) {
                    // TODO Auto-generated method stub
    
                }
            }, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);