android手机旋转方向识别
private OrientationEventListener mOrientationListener; private String TAG = "MainActivity"; private int screenCurOrient = 2; //1表示正竖屏,2表示正横屏,3表示反竖屏,4表示反横屏 private final void startOrientationChangeListener() { mOrientationListener = new OrientationEventListener(this) { @Override public void onOrientationChanged(int rotation) { //判断四个方向 if (rotation == -1) { Log.d(TAG, "手机平放:" + rotation); } else if (rotation < 10 || rotation > 350) { screenOrientChange(1); } else if (rotation < 100 && rotation > 80) { screenOrientChange(4); } else if (rotation < 190 && rotation > 170) { screenOrientChange(3); } else if (rotation < 280 && rotation > 260) { screenOrientChange(2); } else { } } }; mOrientationListener.enable(); } private void screenOrientChange(int Orient) { if(Orient != screenCurOrient) { screenCurOrient = Orient; switch (screenCurOrient) { case 1: Log.d(TAG, "正竖屏:"); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; case 2: Log.d(TAG, "正横屏:"); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; case 3: Log.d(TAG, "反竖屏:"); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; case 4: Log.d(TAG, "反横屏:"); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; } } }
在onCreate方法中调用startOrientationChangeListener方法即可。
人生没有失败,只有自我放弃;只要不放弃,梦想总有一天会变成现实。