200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > Android实现屏幕自动旋转功能

Android实现屏幕自动旋转功能

时间:2021-01-06 04:35:45

相关推荐

Android实现屏幕自动旋转功能

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

直接看代码

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

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

class MyOrientoinListener extends OrientationEventListener {public MyOrientoinListener(Context context) {super(context);}public MyOrientoinListener(Context context, int rate) {super(context, rate);}@Overridepublic 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里取消监听

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

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

作者:吾若成疯

链接:/p/06713cbbd5fe

來源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。