Check orientation on Android phone
Asked Answered
V

24

472

How can I check if the Android phone is in Landscape or Portrait?

Violative answered 8/5, 2010 at 22:10 Comment(3)
Take a look at this answer on a similar thread: https://mcmap.net/q/76971/-android-temporarily-disable-orientation-changes-in-an-activityTalented
why don't just add a Kotlin tag, makes it easier to find on searches with Kotlin keywordSynonymous
@Magic Hands Pellegrin: That question isn't releated. We (those of us who wasted time going off to look at the other thread) would be grateful if you would delete your comment.Zebu
F
761

The current configuration, as used to determine which resources to retrieve, is available from the Resources' Configuration object:

getResources().getConfiguration().orientation;

You can check for orientation by looking at its value:

int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
    // In landscape
} else {
    // In portrait
}

More information can be found in the Android Developer.

Foveola answered 9/5, 2010 at 20:6 Comment(7)
Oh sorry I misunderstood, I thought you were saying that the service wouldn't see the configuration change if the configuration changes. What you are describing is that... well, it isn't seeing anything, because nothing is changing, because the launcher has locked the screen orientation and doesn't allow it to change. So it is correct that .orientation doesn't change, because the orientation hasn't changed. The screen is still portrait.Foveola
The closest thing I can do is to read the orientation from the sensors which involves math that I am not really too keen on figuring out at the moment.Consider
There is nothing to be annoyed about. The screen hasn't rotated, it is still in portrait, there is no rotation to see. If you want to monitor how the user is moving their phone regardless of how the screen is being rotated, then yes you need to directly watch the sensor, and decide how you want to interpret the information you get about how the device is moving.Foveola
exactly, my use case is to determine if the phone is on "landscape" usually when it is in my car dock before it activates car mode along with bluetooth being connected and powered. However, because of this I would have a harder time putting that as an extra case.Consider
This will fail if the screen orientation is fixed.Medan
If the activity locks the display (android:screenOrientation="portrait"), this method will return the same value irrespective of how the user rotates the device. In that case you'd use the accelerometer or the gravity sensor to figure out orientation properly.Meath
this will return true if I split two screenGarges
T
173

If you use getResources().getConfiguration().orientation on some devices you will get it wrong. We used that approach initially in http://apphance.com. Thanks to remote logging of Apphance we could see it on different devices and we saw that fragmentation plays its role here. I saw weird cases: for example alternating portrait and square(?!) on HTC Desire HD:

CONDITION[17:37:10.345] screen: rotation: 270 orientation: square
CONDITION[17:37:12.774] screen: rotation: 0 orientation: portrait
CONDITION[17:37:15.898] screen: rotation: 90
CONDITION[17:37:21.451] screen: rotation: 0
CONDITION[17:38:42.120] screen: rotation: 270 orientation: square

or not changing orientation at all:

CONDITION[11:34:41.134] screen: rotation: 0
CONDITION[11:35:04.533] screen: rotation: 90
CONDITION[11:35:06.312] screen: rotation: 0
CONDITION[11:35:07.938] screen: rotation: 90
CONDITION[11:35:09.336] screen: rotation: 0

On the other hand, width() and height() is always correct (it is used by window manager, so it should better be). I'd say the best idea is to do the width/height checking ALWAYS. If you think about a moment, this is exactly what you want - to know if width is smaller than height (portrait), the opposite (landscape) or if they are the same (square).

Then it comes down to this simple code:

public int getScreenOrientation()
{
    Display getOrient = getWindowManager().getDefaultDisplay();
    int orientation = Configuration.ORIENTATION_UNDEFINED;
    if(getOrient.getWidth()==getOrient.getHeight()){
        orientation = Configuration.ORIENTATION_SQUARE;
    } else{ 
        if(getOrient.getWidth() < getOrient.getHeight()){
            orientation = Configuration.ORIENTATION_PORTRAIT;
        }else { 
             orientation = Configuration.ORIENTATION_LANDSCAPE;
        }
    }
    return orientation;
}
Therapsid answered 4/6, 2011 at 10:11 Comment(4)
Thanks! Initializing "orientation" is superfluous though.Rev
getWidth and getHeight are not deprecated.Niehaus
@user3441905, yes they are. Use getSize(Point outSize) instead. I'm using API 23.Ulla
@jarek-potiuk it is deprecated.Jannery
B
57

Another way of solving this problem is by not relying on the correct return value from the display but relying on the Android resources resolving.

Create the file layouts.xml in the folders res/values-land and res/values-port with the following content:

res/values-land/layouts.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_landscape">true</bool>
</resources>

res/values-port/layouts.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_landscape">false</bool>
</resources>

In your source code you can now access the current orientation as follows:

context.getResources().getBoolean(R.bool.is_landscape)
Brenda answered 18/2, 2013 at 4:0 Comment(2)
I like this as it uses whatever way the system is already determining orientationTighten
What will be its value in default values file?Robson
E
51

A fully way to specify the current orientation of the phone:

public String getRotation(Context context) {
    final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
    switch (rotation) {
        case Surface.ROTATION_0:
            return "portrait";
        case Surface.ROTATION_90:
            return "landscape";
        case Surface.ROTATION_180:
            return "reverse portrait";
        default:
            return "reverse landscape";
    }
}
Emelina answered 4/5, 2012 at 16:55 Comment(6)
There is a typo in your post - it should say .getRotation() not getOrientationClemons
+1 for this. I needed to know exact orientation, not just landscape vs portrait. getOrientation() is correct unless you are on SDK 8+ in which case you should use getRotation(). The 'reverse' modes are supported in SDK 9+.Brenda
@Clemons @Brenda I don't remember how getOrientation() works, but this is not correct if using getRotation(). Get rotation "Returns the rotation of the screen from its "natural" orientation." source. So on a phone saying ROTATION_0 is portrait is likely correct, but on a tablet its "natural" orientation is likely landscape and ROTATION_0 should return landscape instead of portrait.Florinda
Looks like this is the preferred method join forward: developer.android.com/reference/android/view/…Prepense
This is a wrong answer. Why did it get voted? getOrientation(float[] R, float[] values) computes the device's orientation based on the rotation matrix.Stern
like @Clemons @Brenda said, just changing .getOrientation (depricated) to .getRotation() is working like charm even in IntentService :)Orlandoorlanta
G
30

Here is code snippet demo how to get screen orientation was recommend by hackbod and Martijn:

❶ Trigger when change Orientation:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
        int nCurrentOrientation = _getScreenOrientation();
    _doSomeThingWhenChangeOrientation(nCurrentOrientation);
}

❷ Get current orientation as hackbod recommend:

private int _getScreenOrientation(){    
    return getResources().getConfiguration().orientation;
}

❸There are alternative solution for get current screen orientation ❷ follow Martijn solution:

private int _getScreenOrientation(){
        Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        return display.getOrientation();
}

Note: I was try both implement ❷ & ❸, but on RealDevice (NexusOne SDK 2.3) Orientation it returns the wrong orientation.

★So i recommend to used solution ❷ to get Screen orientation which have more advantage: clearly, simple and work like a charm.

★Check carefully return of orientation to ensure correct as our expected (May be have limited depend on physical devices specification)

Hope it help,

Glassworks answered 22/2, 2011 at 0:16 Comment(0)
O
16
int ot = getResources().getConfiguration().orientation;
switch(ot)
        {

        case  Configuration.ORIENTATION_LANDSCAPE:

            Log.d("my orient" ,"ORIENTATION_LANDSCAPE");
        break;
        case Configuration.ORIENTATION_PORTRAIT:
            Log.d("my orient" ,"ORIENTATION_PORTRAIT");
            break;

        case Configuration.ORIENTATION_SQUARE:
            Log.d("my orient" ,"ORIENTATION_SQUARE");
            break;
        case Configuration.ORIENTATION_UNDEFINED:
            Log.d("my orient" ,"ORIENTATION_UNDEFINED");
            break;
            default:
            Log.d("my orient", "default val");
            break;
        }
Orelle answered 22/7, 2011 at 7:15 Comment(0)
C
15

Some time has passed since most of these answers have been posted and some use now deprecated methods and constants.

I've updated Jarek's code to not use these methods and constants anymore:

protected int getScreenOrientation()
{
    Display getOrient = getWindowManager().getDefaultDisplay();
    Point size = new Point();

    getOrient.getSize(size);

    int orientation;
    if (size.x < size.y)
    {
        orientation = Configuration.ORIENTATION_PORTRAIT;
    }
    else
    {
        orientation = Configuration.ORIENTATION_LANDSCAPE;
    }
    return orientation;
}

Note that the mode Configuration.ORIENTATION_SQUARE isn't supported anymore.

I found this to be reliable on all devices I've tested it on in contrast to the method suggesting the usage of getResources().getConfiguration().orientation

Chyme answered 1/4, 2015 at 13:50 Comment(1)
Note that getOrient.getSize(size) requires 13 api levelYounglove
B
14

Use getResources().getConfiguration().orientation it's the right way.

You just have to watch out for different types of landscapes, the landscape that the device normally uses and the other.

Still don't understand how to manage that.

Brucite answered 25/1, 2011 at 16:0 Comment(0)
G
8

Check screen orientation in runtime.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();

    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();        
    }
}
Golanka answered 13/2, 2013 at 6:20 Comment(0)
C
6

There is one more way of doing it:

public int getOrientation()
{
    if(getResources().getDisplayMetrics().widthPixels>getResources().getDisplayMetrics().heightPixels)
    { 
        Toast t = Toast.makeText(this,"LANDSCAPE",Toast.LENGTH_SHORT);
        t.show();
        return 1;
    }
    else
    {
        Toast t = Toast.makeText(this,"PORTRAIT",Toast.LENGTH_SHORT);
        t.show();
        return 2;
    }       
}
Cauda answered 29/10, 2011 at 9:3 Comment(0)
A
6

Just simple two line code

if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
    // do something in landscape
} else {
    //do in potrait
}
Arrear answered 17/9, 2019 at 16:29 Comment(0)
H
5

The Android SDK can tell you this just fine:

getResources().getConfiguration().orientation
Hl answered 31/5, 2012 at 16:9 Comment(0)
K
5

such this is overlay all phones such as oneplus3

public static boolean isScreenOrientationPortrait(Context context) {
    return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
}

right code as follows:

public static int getRotation(Context context) {
    final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();

    if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
        return Configuration.ORIENTATION_PORTRAIT;
    }

    if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) {
        return Configuration.ORIENTATION_LANDSCAPE;
    }

    return -1;
}
Kolkhoz answered 1/6, 2018 at 6:10 Comment(0)
B
5

Tested in 2019 on API 28, regardless of the user has set portrait orientation or not, and with minimal code compared to another, outdated answer, the following delivers the correct orientation:

/** @return The {@link Configuration#ORIENTATION_SQUARE}, {@link Configuration#ORIENTATION_PORTRAIT}, {@link Configuration#ORIENTATION_LANDSCAPE} constants based on the current phone screen pixel relations. */
private int getScreenOrientation()
{
    DisplayMetrics dm = context.getResources().getDisplayMetrics(); // Screen rotation effected

    if(dm.widthPixels == dm.heightPixels)
        return Configuration.ORIENTATION_SQUARE;
    else
        return dm.widthPixels < dm.heightPixels ? Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
}
Brogdon answered 5/3, 2019 at 11:45 Comment(0)
L
2

I think this code may work after orientation change has take effect

Display getOrient = getWindowManager().getDefaultDisplay();

int orientation = getOrient.getOrientation();

override Activity.onConfigurationChanged(Configuration newConfig) function and use newConfig,orientation if you want to get notified about the new orientation before calling setContentView.

Laskowski answered 26/11, 2011 at 17:54 Comment(0)
M
2

i think using getRotationv() doesn't help because http://developer.android.com/reference/android/view/Display.html#getRotation%28%29 getRotation() Returns the rotation of the screen from its "natural" orientation.

so unless you know the "natural" orientation, rotation is meaningless.

i found an easier way,

  Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
  Point size = new Point();
  display.getSize(size);
  int width = size.x;
  int height = size.y;
  if(width>height)
    // its landscape

please tell me if there is a problem with this someone?

Monograph answered 17/1, 2013 at 9:37 Comment(0)
C
1

Simple and easy :)

  1. Make 2 xml layouts ( i.e Portrait and Landscape )
  2. At java file, write:

    private int intOrientation;
    

    at onCreate method and before setContentView write:

    intOrientation = getResources().getConfiguration().orientation;
    if (intOrientation == Configuration.ORIENTATION_PORTRAIT)
        setContentView(R.layout.activity_main);
    else
        setContentView(R.layout.layout_land);   // I tested it and it works fine.
    
Colier answered 8/5, 2010 at 22:10 Comment(0)
B
1

Old post I know. Whatever the orientation may be or is swapped etc. I designed this function that is used to set the device in the right orientation without the need to know how the portrait and landscape features are organised on the device.

   private void initActivityScreenOrientPortrait()
    {
        // Avoid screen rotations (use the manifests android:screenOrientation setting)
        // Set this to nosensor or potrait

        // Set window fullscreen
        this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        DisplayMetrics metrics = new DisplayMetrics();
        this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

         // Test if it is VISUAL in portrait mode by simply checking it's size
        boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels ); 

        if( !bIsVisualPortrait )
        { 
            // Swap the orientation to match the VISUAL portrait mode
            if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
             { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
            else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
        }
        else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }

    }

Works like a charm!

Bonnard answered 13/3, 2014 at 10:24 Comment(0)
E
1

Use this way,

    int orientation = getResources().getConfiguration().orientation;
    String Orintaion = "";
    switch (orientation)
    {
        case Configuration.ORIENTATION_UNDEFINED: Orintaion = "Undefined"; break;
        case Configuration.ORIENTATION_LANDSCAPE: Orintaion = "Landscrape"; break;
        case Configuration.ORIENTATION_PORTRAIT:  Orintaion = "Portrait"; break;
        default: Orintaion = "Square";break;
    }

in the String you have the Oriantion

Eadmund answered 22/6, 2015 at 18:51 Comment(0)
A
1

there are many ways to do this , this piece of code works for me

 if (this.getWindow().getWindowManager().getDefaultDisplay()
                .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
             // portrait mode
} else if (this.getWindow().getWindowManager().getDefaultDisplay()
                .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                      // landscape
        }
Ankara answered 25/8, 2015 at 12:36 Comment(0)
A
1

I think this solution easy one

if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
  user_todat_latout = true;
} else {
  user_todat_latout = false;
}
Ailyn answered 16/12, 2017 at 3:52 Comment(2)
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.Pooh
yes sorry for that i was think it's doesn't need explain exactly this block of code check orientation if equal Configuration.ORIENTATION_PORTRAIT that's mean app in portrait :)Ailyn
M
0

It's also worth noting that nowadays, there's less good reason to check for explicit orientation with getResources().getConfiguration().orientation if you're doing so for layout reasons, as Multi-Window Support introduced in Android 7 / API 24+ could mess with your layouts quite a bit in either orientation. Better to consider using <ConstraintLayout>, and alternative layouts dependent on available width or height, along with other tricks for determining which layout is being used, e.g. the presence or not of certain Fragments being attached to your Activity.

Matronna answered 21/7, 2018 at 14:13 Comment(0)
A
0

You can use this (based on here) :

public static boolean isPortrait(Activity activity) {
    final int currentOrientation = getCurrentOrientation(activity);
    return currentOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT || currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}

public static int getCurrentOrientation(Activity activity) {
    //code based on https://www.captechconsulting.com/blog/eric-miles/programmatically-locking-android-screen-orientation
    final Display display = activity.getWindowManager().getDefaultDisplay();
    final int rotation = display.getRotation();
    final Point size = new Point();
    display.getSize(size);
    int result;
    if (rotation == Surface.ROTATION_0
            || rotation == Surface.ROTATION_180) {
        // if rotation is 0 or 180 and width is greater than height, we have
        // a tablet
        if (size.x > size.y) {
            if (rotation == Surface.ROTATION_0) {
                result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            }
        } else {
            // we have a phone
            if (rotation == Surface.ROTATION_0) {
                result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            }
        }
    } else {
        // if rotation is 90 or 270 and width is greater than height, we
        // have a phone
        if (size.x > size.y) {
            if (rotation == Surface.ROTATION_90) {
                result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            }
        } else {
            // we have a tablet
            if (rotation == Surface.ROTATION_90) {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            }
        }
    }
    return result;
}
Archine answered 12/11, 2018 at 11:44 Comment(0)
S
0

I think this solution easy one to check is Landscape

 public static boolean isLandscape(Context context) {
    final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
    
    if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
        return false;
    }

    return rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270;
}
Secretory answered 1/9, 2022 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.