Android 横屏旋转180°监听方式 - 简书 (jianshu.com)公司要求实现一个扫码登录的功能,在其他功能实现差不多的时候,忽然发现,当屏幕旋转180°的时候,相机的方向也会跟着反转,这不是我想要的结果。在网上发现绝大部分的帖子都是教如何解决横竖屏幕切换的,但由于我们的项目是要保持横屏操作,所以不用考虑横竖切换。但是目前所有的智能机都可以进行横屏的180度旋转,所以纪录一下解决过程。
横屏180°旋转系统不会回调到到
onConfigurationChanged(),只能使用其他的方案,目前有2个方案
1、使用OrientationEventListener 监听屏幕的旋转,里面本质使用的是
TYPE_ACCELEROMETER传感器,具体如下:(我用了,但是没有解决我的问题)
public class MyOrientationDetector extends OrientationEventListener {
public MyOrientationDetector(Context context) {
super(context);
}
@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.i("MyOrientationDetector ","onOrientationChanged:"+orientation);
}
}
这个方法需要定义一个MyOrientationDetector类并继承OrientationEventListener。同时需要在activity中创建MyOrientationDetector对象并在onResume中开启调用mOrientationListener. enable(),在onPause中关闭调用mOrientationListener. disable()。
这种方式对性能消耗比较大, 但是可以获取到手机当前的角度。
2、使用监听DisplayManager方式,手机切换方向会导致UI 显示的改变,所以会回调到这里
DisplayManager.DisplayListener mDisplayListener = new DisplayManager.DisplayListener() {
@Override
public void onDisplayAdded(int displayId) {
android.util.Log.i(TAG, "Display #" + displayId + " added.");
}
@Override
public void onDisplayChanged(int displayId) {
android.util.Log.i(TAG, "Display #" + displayId + " changed.");
}
@Override
public void onDisplayRemoved(int displayId) {
android.util.Log.i(TAG, "Display #" + displayId + " removed.");
}
};
DisplayManager displayManager = (DisplayManager) mContext.getSystemService(Context.DISPLAY_SERVICE);
displayManager.registerDisplayListener(mDisplayListener, UIThreadHandler);
(因为我不需要获取手机当前的角度,只需要知道有没有旋转即可,所以我使用的这中方式)