Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect orientation change, when only portrait is allowed on Android

I have to solve the following: I have an Activity which's android:screenOrientation="portrait". Even though, when the device is rotated to landscape while this Activity is visible, I have to start another one, and, when the device is rotated back to portrait, I have to finish() the activity in landscape. I tried to perform this with a BroadcastReceiver, but this special activity doesn't receive any broadcasts because of the android:screenOrientation="portrait". Any help is well appreciated.

Thanks.

like image 912
overbet13 Avatar asked Dec 09 '22 21:12

overbet13


1 Answers

Philipp's solution in Get phone orientation but fix screen orientation to portrait work's perfectly for me:

You can use the SensorManager class to get the orientation of the Android device, even when the automatic orientation switching is disabled in the Manifest by android:screenOrientation="portrait"

See this code (by Philipp, see link above):

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);
like image 165
Wile E. Genius Avatar answered May 14 '23 11:05

Wile E. Genius