当前位置: 移动技术网 > 移动技术>移动开发>Android > Android 屏幕旋转使用OrientationEventListener实时监听

Android 屏幕旋转使用OrientationEventListener实时监听

2020年07月09日  | 移动技术网移动技术  | 我要评论

在开发Camera的时候,总是会遇到一些旋转效果,因为camera在AndroidMenifest.xml中设置android:screenOrientation=“portrait”,所以需要使用一些特别的方式监听手机的旋转角度:
OrientationEventListener 的监听不只是判断屏幕旋转角度0,90,180,270 四个角度,还可以实时获取每一个角度的变化。
使用方法:

(1)创建一个类继承OrientationEventListener

(2)开启和关闭监听

可以在 activity 中创建MyOrientationDetector 类的对象,注意,监听的开启的关闭,是由该类的父类的 enable() 和 disable() 方法实现的。

因此,可以在activity的 onResume() 中调用MyOrientationDetector 对象的 enable方法,在 onPause() 中调用MyOrientationDetector 对象的 disable方法来完车功能。

(3)监测指定的屏幕旋转角度

MyOrientationDetector类的onOrientationChanged 参数orientation是一个从0~359的变量,如果只希望处理四个方向,加一个判断即可:

 OrientationEventListener mOrientationListener;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        mOrientationListener = new OrientationEventListener(this,
            SensorManager.SENSOR_DELAY_NORMAL) {
 
            @Override
            public void onOrientationChanged(int orientation) {
            if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
			    return;  //手机平放时,检测不到有效的角度
			}
			//只检测是否有四个角度的改变
			if (orientation > 350 || orientation < 10) { //0度
			    orientation = 0;
			} else if (orientation > 80 && orientation < 100) { //90度
			    orientation = 90;
			} else if (orientation > 170 && orientation < 190) { //180度
			    orientation = 180;
			} else if (orientation > 260 && orientation < 280) { //270度
			    orientation = 270;
			} else {
			    return;
			}
			Log.v(DEBUG_TAG,"Orientation changed to " + orientation);
            }
        };
 
       if (mOrientationListener.canDetectOrientation()) {
           Log.v(DEBUG_TAG, "Can detect orientation");
           mOrientationListener.enable();
       } else {
           Log.v(DEBUG_TAG, "Cannot detect orientation");
           mOrientationListener.disable();
       }
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mOrientationListener.disable();
    }

以上就是屏幕旋转处理的方式,上面的代码是可以直接使用,可以写个DEMO试试就能理解了。

本文地址:https://blog.csdn.net/haiping1224746757/article/details/107150390

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网