Android: get device orientation from Azimuth, roll & pitch

前端 未结 1 574
春和景丽
春和景丽 2020-12-13 11:52

I need to get the updated device orientation, but I have to fix my activity to Portrait (which I did in the layout xml file), which prevents me from using this:



        
相关标签:
1条回答
  • 2020-12-13 12:12

    I've found it & here is the calculating function that will be called inside the listener after reading the pitch & roll:

    public static final int ORIENTATION_PORTRAIT = 0;
    public static final int ORIENTATION_LANDSCAPE_REVERSE = 1;
    public static final int ORIENTATION_LANDSCAPE = 2;
    public static final int ORIENTATION_PORTRAIT_REVERSE = 3;
    public int orientation = ORIENTATION_PORTRAIT;
    
    private int calculateOrientation(int roll, int pitch) {
        if (((orientation == ORIENTATION_PORTRAIT || orientation == ORIENTATION_PORTRAIT_REVERSE)
                && (roll > -30 && roll < 30))) {
            if (averagePitch > 0)
                return ORIENTATION_PORTRAIT_REVERSE;
            else
                return ORIENTATION_PORTRAIT;
        } else {
            // divides between all orientations
            if (Math.abs(pitch) >= 30) {
                if (pitch > 0)
                    return ORIENTATION_PORTRAIT_REVERSE;
                else
                    return ORIENTATION_PORTRAIT;
            } else {
                if (averageRoll > 0) {
                    return ORIENTATION_LANDSCAPE_REVERSE;
                } else {
                    return ORIENTATION_LANDSCAPE;
                }
            }
        }
    }
    

    -- Update --

    & here is my full utility class implementation

    -- Update --

    Adding this image to help visualizing the azimuth, pitch & roll:

    0 讨论(0)
提交回复
热议问题