Android实现屏幕自动旋转功能

来源:互联网 发布:农村淘宝合伙人亏死 编辑:程序博客网 时间:2024/06/08 02:17

最近在做一个视频客户端项目,有一个功能是,视频要实现自动旋转功能,在这里做一简单的总结。实现起来很简单,几行代码就能够搞定。

直接看代码

1、继承OrientationEventListener类监听手机的旋转

这里用到的是OrientationEventListener类,它是当手机屏幕旋转时从SensorManger接受通知的助手类。新建一个类继承OrientationEventListener,如下

class MyOrientoinListener extends OrientationEventListener {        public MyOrientoinListener(Context context) {            super(context);        }        public MyOrientoinListener(Context context, int rate) {            super(context, rate);        }        @Override        public void onOrientationChanged(int orientation) {            Log.d(TAG, "orention" + orientation);            int screenOrientation = getResources().getConfiguration().orientation;            if (((orientation >= 0) && (orientation < 45)) || (orientation > 315)) {//设置竖屏                if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && orientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {                    Log.d(TAG, "设置竖屏");                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);                    oriBtn.setText("竖屏");                }            } else if (orientation > 225 && orientation < 315) { //设置横屏                Log.d(TAG, "设置横屏");                if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);                    oriBtn.setText("横屏");                }            } else if (orientation > 45 && orientation < 135) {// 设置反向横屏                Log.d(TAG, "反向横屏");                if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);                    oriBtn.setText("反向横屏");                }            } else if (orientation > 135 && orientation < 225) {                Log.d(TAG, "反向竖屏");                if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);                    oriBtn.setText("反向竖屏");                }            }        }    }

2、在Activity中开启自动旋转

  myOrientoinListener = new MyOrientoinListener(this);  boolean autoRotateOn = (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1);  //检查系统是否开启自动旋转  if (autoRotateOn) {      myOrientoinListener.enable();   }

3、Activity销毁时在onDesotry里取消监听

    @Override    protected void onDestroy() {        super.onDestroy();        //销毁时取消监听        myOrientoinListener.disable();    }

这样就实现了屏幕自动旋转的功能了,很简单有木有!



作者:吾若成疯
链接:http://www.jianshu.com/p/06713cbbd5fe
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
原创粉丝点击