民浩

 

android手机旋转方向识别

private OrientationEventListener mOrientationListener;
    private String TAG = "MainActivity";
    private int screenCurOrient = 2; //1表示正竖屏,2表示正横屏,3表示反竖屏,4表示反横屏

    private final void startOrientationChangeListener() {
        mOrientationListener = new OrientationEventListener(this) {
            @Override
            public void onOrientationChanged(int rotation) {
                //判断四个方向
                if (rotation == -1) {
                    Log.d(TAG, "手机平放:" + rotation);
                } else if (rotation < 10 || rotation > 350) {
                    screenOrientChange(1);
                } else if (rotation < 100 && rotation > 80) {
                    screenOrientChange(4);
                } else if (rotation < 190 && rotation > 170) {
                    screenOrientChange(3);
                } else if (rotation < 280 && rotation > 260) {
                    screenOrientChange(2);
                }
                else
                {
                }
            }
        };
        mOrientationListener.enable();
    }

    private void screenOrientChange(int Orient)
    {
        if(Orient != screenCurOrient)
        {
            screenCurOrient = Orient;
            switch (screenCurOrient)
            {
                case 1:
                    Log.d(TAG, "正竖屏:");
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    break;
                case 2:
                    Log.d(TAG, "正横屏:");
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    break;
                case 3:
                    Log.d(TAG, "反竖屏:");
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    break;
                case 4:
                    Log.d(TAG, "反横屏:");
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    break;
            }
        }
    }

onCreate方法中调用startOrientationChangeListener方法即可。

 

posted on 2017-08-23 11:39  民浩  阅读(1422)  评论(0编辑  收藏  举报

导航