获取Android设备的方向

And*_*Dev 7 android orientation

你会认为会有一个直接的解决方案.Android文档说明:

方向传感器在Android 2.2(API级别8)中已弃用.我们建议您将getRotationMatrix()方法与getOrientation()方法结合使用以计算方向值,而不是使用方向传感器中的原始数据.

然而,他们没有提供如何实施getOrientation()和实施的解决方案getRotationMatrix().我花了几个小时在这里阅读使用这些方法的开发人员的帖子,但他们都有部分粘贴的代码或一些奇怪的实现.谷歌搜索没有提供教程.有人可以使用这两种方法粘贴一个简单的解决方案来生成方向吗?

Nip*_*gia 6

以下是实施getOrientation():

public int getscrOrientation()
    {
        Display getOrient = getWindowManager().getDefaultDisplay();

        int orientation = getOrient.getOrientation();

        // Sometimes you may get undefined orientation Value is 0
        // simple logic solves the problem compare the screen
        // X,Y Co-ordinates and determine the Orientation in such cases
        if(orientation==Configuration.ORIENTATION_UNDEFINED){

            Configuration config = getResources().getConfiguration();
            orientation = config.orientation;

            if(orientation==Configuration.ORIENTATION_UNDEFINED){
                //if height and widht of screen are equal then
                // it is square orientation
                if(getOrient.getWidth()==getOrient.getHeight()){
                    orientation = Configuration.ORIENTATION_SQUARE;
                }else{ //if widht is less than height than it is portrait
                    if(getOrient.getWidth() < getOrient.getHeight()){
                        orientation = Configuration.ORIENTATION_PORTRAIT;
                    }else{ // if it is not any of the above it will definitely be landscape
                        orientation = Configuration.ORIENTATION_LANDSCAPE;
                    }
                }
            }
        }
        return orientation; // return value 1 is portrait and 2 is Landscape Mode
    }
Run Code Online (Sandbox Code Playgroud)

您还可以参考此示例,它代表两种方法的使用:

     getOrientation and getRotationMatrix
Run Code Online (Sandbox Code Playgroud)

http://www.codingforandroid.com/2011/01/using-orientation-sensors-simple.html