简体   繁体   中英

Android: Get physical device orientation in a portrait-only app

My app is locked into portrait orientation only, however in one fragment I have a camera preview where I would like to rotate captured images based on the device orientation. I believe that because my app is portrait only, the following code always logs zero.

Display display = ((WindowManager)getActivity().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
Log.i(TAG, "Rotation: " + rotation );

Is it possible to get the actual orientation of the device while locking the app to portrait?

I am targeting android 4.0+ so I'm not concerned if the solution won't work on older devices.

you could implement a SensorEventListener, then look at the Roll in onSensorChanged:

@Override
public void onSensorChanged(SensorEvent event) {    

    synchronized(this)
    {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            mAccelerometerValues = event.values;     
        }           
        if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            mGeomageneticValues = event.values;     
        }       

        if ((mAccelerometerValues != null) && (mGeomageneticValues != null))
        {

            boolean success = SensorManager.getRotationMatrix(R, I, mAccelerometerValues, mGeomageneticValues);
            if (success)
            {
                SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_X, SensorManager.AXIS_Z, outR); 
                SensorManager.getOrientation(outR,orientation);
                mYaw = orientation[0] * MathX.toDegreesF;               
                mPitch = orientation[1] * MathX.toDegreesF;
                mRoll = orientation[2] * MathX.toDegreesF;

                String sText = String.format("a:%1.4f\np:%1.4f\nr:%1.4f", yaw,pitch,roll); 



            }


        }
    }




}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM