Detecting device orientation

风格不统一 提交于 2019-12-04 07:05:45
razzak

By setting screenOrientation property in Manifest you won't be able to get orientation value from onConfigurationChanged anymore as it would stop firing, it's possible to implement SensorEventListener to obtain Pitch, roll and yaw angles to calculate the orientation, but it's a bit complicated and an overkill for such a task. The best solution i found is to use OrientationEventListener, the following code will update rotation value on orientation change, the value is 0 to 4 according to the rotation angle:

private OrientationEventListener listener;
private int rotation;

@Override
protected void onCreate (Bundle savedInstanceState)
{
    super.onCreate (savedInstanceState);
    setContentView (R.layout.main);

    listener = new OrientationEventListener (this, SensorManager.SENSOR_DELAY_NORMAL)
    {
        @Override
        public void onOrientationChanged (int orientation)
        {
            rotation = ((orientation + 45) / 90) % 4;
        }
    };

    if (myOrientationEventListener.canDetectOrientation()) listener.enable();
    else listener = null; // Orientation detection not supported
}

@Override
protected void onDestroy()
{
    super.onDestroy();
    if (listener != null) listener.disable();
}

My activity is set to always be in portrait mode. Put this code onCreate.

    myOrientationEventListener = new OrientationEventListener(this,SensorManager.SENSOR_DELAY_NORMAL) {
        public void onOrientationChanged(int arg0) {
            if (arg0>=315 || arg0<45){
                currentOrientation = Surface.ROTATION_90;
            }else if (arg0>=45 && arg0<135){
                currentOrientation = Surface.ROTATION_180;
            }else if (arg0>=135 && arg0<225){
                currentOrientation = Surface.ROTATION_270;
            }else if (arg0>=225 && arg0<315){
                currentOrientation = Surface.ROTATION_0;
            }
        }
    };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!