How to check orientation of your Android device in real time

整理转载自ticktick

在对应的activity中,重载函数onConfigurationChanged

1
2
3
4
@Override
public voidonConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}

在该函数中可以通过两种方法检测当前的屏幕状态:

  • 判断newConfig是否等于

    1
    2
    Configuration.ORIENTATION_LANDSCAPE,
    Configuration.ORIENTATION_PORTRAIT

    当然,这种方法只能判断屏幕是否为横屏,或者竖屏,不能获取具体的旋转角度.

  • 调用

    1
    this.getWindowManager().getDefaultDisplay().getRotation();

    该函数的返回值,有如下四种:

    1
    2
    3
    4
    Surface.ROTATION_0,
    Surface.ROTATION_90,
    Surface.ROTATION_180,
    Surface.ROTATION_270

    其中,Surface.ROTATION_0 表示的是手机竖屏方向向上,后面几个以此为基准依次以顺时针90度递增.

    Bug: 它只能一次旋转90度, 如果你突然一下子旋转180度, onConfigurationChanged函数不会被调用.

实时判断屏幕旋转的每一个角度

上面说的各种屏幕旋转角度的判断至多只能判断 0, 90 , 180, 270 四个角度,如果希望实时获取每一个角度的变化,则可以通过OrientationEventListener 来实现.

  • 创建一个类继承OrientationEventListener

    1
    2
    3
    4
    5
    6
    7
    8
    9
    public class MyOrientationDetector extends OrientationEventListener{
    public MyOrientationDetector( Context context ) {
    super(context );
    }
    @Override
    public void onOrientationChanged(int orientation) {
    Log.i("MyOrientationDetector ","onOrientationChanged:"+orientation);
    }
    }
  • 开启和关闭监听
    可以在 activity 中创建MyOrientationDetector 类的对象,注意,监听的开启的关闭,是由该类的父类的 enable() 和 disable() 方法实现的.
    因此,可以在activity的
    onResume() 中调用MyOrientationDetector 对象的 enable方法,
    onPause() 中调用MyOrientationDetector 对象的 disable方法来完成功能.

  • 监测指定的屏幕旋转角度

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    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);