Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Android device's physical orientation in degrees.

Tags:

android

I know that I have to use the class OrientationListener to get the angle from the device. I want to get the angle between -90° and 90°. I don't know how to do it. picture on the left: 90 degree, picture in the middle: 0 degree and picture on the right: -90 degree

90 degree0 degree-90 degree

Code

class OrientationListener implements SensorEventListener
{

    @Override
    public void onSensorChanged(SensorEvent event)
    {
        angle = Math.round(event.values[2]);

        if (angle < 0)
        {
            angle = angle * -1;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy)
    {
    }
}
like image 906
funk Avatar asked Oct 01 '22 07:10

funk


2 Answers

You can use this code for simple 0, 90, 180 degrees.

Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

int rotation = display.getRotation();

Surface.ROTATION_0 is 0 degrees, Surface,ROTATION_90 is 90 degrees etc.

You can also use SensorEventListener interface if you want the degrees other than 0, 90, etc:

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

        float rawX = event.values[0];
    }
}

You'd need to get use this code to get the degrees:

double k = 90/9.8;
double degrees = rawX * k; // this is a rough estimate of degrees, converted from gravity
like image 137
ElectronicGeek Avatar answered Oct 05 '22 13:10

ElectronicGeek


This is a working example.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView tv = new TextView(this);
    setContentView(tv);

    Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
    int rotation = display.getRotation();

    String rotString="";
    switch(rotation) {
    case Surface.ROTATION_0:
        rotString="portrait";
        break;
    case Surface.ROTATION_90:
        rotString="landscape left";
        break;
    case Surface.ROTATION_180:
        rotString="flipped portrait";
        break;
    case Surface.ROTATION_270:
        rotString="landscape right";
        break;
    }

    tv.setText(rotString);

}
like image 34
ElDuderino Avatar answered Oct 05 '22 12:10

ElDuderino