get Device Natural Orientation - Android User Interface

Android examples for User Interface:Screen Orientation

Description

get Device Natural Orientation

Demo Code


//package com.java2s;
import android.content.Context;
import android.content.res.Configuration;

import android.view.Surface;
import android.view.WindowManager;

public class Main {
    public static int getDeviceNaturalOrientation(Context context) {
        final int currentOrientation = getDeviceCurrentOrientation(context);

        if (currentOrientation == Configuration.ORIENTATION_UNDEFINED) {
            return Configuration.ORIENTATION_UNDEFINED;
        }/* ww  w. j  a  v  a2s  .  c o m*/

        final WindowManager windowManager = getWindowManager(context);
        final int currentRotation = windowManager.getDefaultDisplay()
                .getRotation();

        if (currentRotation != Surface.ROTATION_0
                && currentRotation != Surface.ROTATION_90
                && currentRotation != Surface.ROTATION_180
                && currentRotation != Surface.ROTATION_270) {
            return Configuration.ORIENTATION_UNDEFINED;
        }

        if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            if (currentRotation == Surface.ROTATION_0
                    || currentRotation == Surface.ROTATION_180) {
                return Configuration.ORIENTATION_PORTRAIT;
            }
            return Configuration.ORIENTATION_LANDSCAPE;
        }

        if (currentRotation == Surface.ROTATION_0
                || currentRotation == Surface.ROTATION_180) {
            return Configuration.ORIENTATION_LANDSCAPE;
        }

        return Configuration.ORIENTATION_PORTRAIT;
    }

    public static int getDeviceCurrentOrientation(Context context) {
        int orientation = context.getResources().getConfiguration().orientation;
        if (orientation != Configuration.ORIENTATION_LANDSCAPE
                && orientation != Configuration.ORIENTATION_PORTRAIT) {
            return Configuration.ORIENTATION_UNDEFINED;
        }
        return orientation;
    }

    private static WindowManager getWindowManager(Context context) {
        return (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
    }
}

Related Tutorials