0

In my app I have set preferred orientations of portrait

SystemChrome.setPreferredOrientations([
  DeviceOrientation.portraitUp,
])

But I would like to listen for changes in the orientation without changing what is displayed on the screen

I want to listen for orientation changes even though it is locked

I would like some code equivalent to this

MediaQuery.of(context).orientation

However, since I have locked it to portrait it will always say portrait

GILO
  • 2,444
  • 21
  • 47

2 Answers2

0

You can use SensorManager class for this:

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);

There are also other ways you can check in this post: Get phone orientation but fix screen orientation to portrait

sak
  • 1,230
  • 18
  • 37
0

I suggest using this package native_device_orientation it provides accurate orientation and doesn't just look at the devices width.

// Gets the devices orientation
NativeDeviceOrientation orientation = await NativeDeviceOrientationCommunicator().orientation(useSensor:true);
GILO
  • 2,444
  • 21
  • 47