Get the natural orientation of the device. - Android Hardware

Android examples for Hardware:Device Feature

Description

Get the natural orientation of the device.

Demo Code


//package com.java2s;
import android.app.Activity;
import android.content.res.Configuration;
import android.util.Log;
import android.view.Display;
import android.view.Surface;

public class Main {
    public static final String TAG = "AndroidUtil";

    /**//from  ww  w. ja  va 2  s  . c  o  m
     *  Get the natural orientation of the device.
     * @param activity
     * @return Configuration.ORIENTATION_LANDSCAPE or Configuration.ORIENTATION_PORTRAIT.
     */
    public static int getNaturalOrientation(Activity activity) {
        int naturalOrientation = Configuration.ORIENTATION_UNDEFINED;

        Display display = activity.getWindowManager().getDefaultDisplay();
        int rotation = display.getRotation();

        Log.d(TAG, "" + rotation);

        Configuration configuration = activity.getResources()
                .getConfiguration();
        if (Configuration.ORIENTATION_LANDSCAPE == configuration.orientation) {
            if (Surface.ROTATION_0 == rotation
                    || Surface.ROTATION_180 == rotation) {
                naturalOrientation = Configuration.ORIENTATION_LANDSCAPE;
            } else {
                naturalOrientation = Configuration.ORIENTATION_PORTRAIT;
            }
        } else {
            if (Surface.ROTATION_0 == rotation
                    || Surface.ROTATION_180 == rotation) {
                naturalOrientation = Configuration.ORIENTATION_PORTRAIT;
            } else {
                naturalOrientation = Configuration.ORIENTATION_LANDSCAPE;
            }
        }
        return naturalOrientation;
    }
}

Related Tutorials