获取Android设备的方向

您会认为会有一个直接的解决方案. Android文档声明

The orientation sensor was deprecated in Android 2.2 (API level 8).
Instead of using raw data from the orientation sensor,we recommend
that you use the getRotationMatrix() method in conjunction with the
getorientation() method to compute orientation values.

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

解决方法

以下是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
    }

你也可以参考这个代表两种方法使用的例子:

getorientation and getRotationMatrix

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

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...