Android实现屏幕自动旋转

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

直接看代码

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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中开启自动旋转

1
2
3
4
5
6
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里取消监听

1
2
3
4
5
6
@Override
protected void onDestroy() {
super.onDestroy();
//销毁时取消监听
myOrientoinListener.disable();
}

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

Demo地址:https://github.com/xingchenfengn/ScreenAutoRotateDemo.git