470

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

Mohit Deshpande
  • 53,877
  • 76
  • 193
  • 251
  • 1
    Take a look at this answer on a similar thread: http://stackoverflow.com/a/26601009/3072449 – Magic Hands Pellegrin Oct 28 '14 at 05:15
  • why don't just add a Kotlin tag, makes it easier to find on searches with Kotlin keyword – Harsh Jul 03 '21 at 20:00
  • 1
    @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. – Robin Davies Apr 17 '22 at 03:09

24 Answers24

757

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.

AlexS
  • 918
  • 1
  • 12
  • 28
hackbod
  • 90,665
  • 16
  • 140
  • 154
  • 2
    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. – hackbod Feb 23 '12 at 08:32
  • 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. – Archimedes Trajano Feb 23 '12 at 18:21
  • 13
    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. – hackbod Feb 24 '12 at 04:30
  • 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. – Archimedes Trajano Feb 24 '12 at 05:59
  • 4
    This will fail if the screen orientation is fixed. – Johann Jul 30 '13 at 14:27
  • 7
    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. – Cat Aug 21 '14 at 23:08
  • this will return true if I split two screen – vishal patel Jun 06 '19 at 06:32
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;
}
Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
Jarek Potiuk
  • 19,317
  • 2
  • 60
  • 61
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)
Paul
  • 3,077
  • 2
  • 18
  • 20
50

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";
    }
}
Emma
  • 27,428
  • 11
  • 44
  • 69
Nguyen Minh Binh
  • 23,891
  • 30
  • 115
  • 165
  • 6
    There is a typo in your post - it should say .getRotation() not getOrientation – Keith Aug 25 '12 at 23:44
  • 1
    +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+. – Paul Oct 16 '12 at 20:54
  • 7
    @Keith @Paul 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](http://developer.android.com/reference/android/view/Display.html#getRotation()). 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. – jp36 Jan 16 '13 at 18:55
  • Looks like this is the preferred method join forward: http://developer.android.com/reference/android/view/Display.html#getRotation() – jaysqrd Feb 18 '13 at 09:26
  • 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. – user1914692 Jul 20 '13 at 23:24
  • like @Keith @Paul said, just changing `.getOrientation` (depricated) to `.getRotation()` is working like charm even in IntentService :) – Choletski Jul 23 '15 at 13:56
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,

Community
  • 1
  • 1
NguyenDat
  • 4,129
  • 3
  • 46
  • 46
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;
        }
Taryn
  • 242,637
  • 56
  • 362
  • 405
anshul
  • 161
  • 1
  • 2
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

Community
  • 1
  • 1
Baz
  • 36,440
  • 11
  • 68
  • 94
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.

skwear
  • 563
  • 1
  • 5
  • 24
neteinstein
  • 17,529
  • 11
  • 93
  • 123
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();        
    }
}
Kumar
  • 442
  • 1
  • 9
  • 19
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;
    }       
}
Michael Dillon
  • 31,973
  • 6
  • 70
  • 106
mchouhan_google
  • 1,775
  • 1
  • 20
  • 28
5

The Android SDK can tell you this just fine:

getResources().getConfiguration().orientation
Peter Lang
  • 54,264
  • 27
  • 148
  • 161
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;
}
shb
  • 5,957
  • 2
  • 15
  • 32
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;
}
ManuelTS
  • 316
  • 4
  • 14
5

Just simple two line code

if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
    // do something in landscape
} else {
    //do in potrait
}
Rezaul Karim
  • 830
  • 8
  • 15
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?

steveh
  • 1,352
  • 2
  • 27
  • 41
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.

Daniel
  • 41
  • 1
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!

Codebeat
  • 6,501
  • 6
  • 57
  • 99
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

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
        }
Mehroz Munir
  • 2,248
  • 1
  • 18
  • 16
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.
    
Benny
  • 2,233
  • 1
  • 22
  • 27
Kerelos
  • 83
  • 4
1

I think this solution easy one

if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
  user_todat_latout = true;
} else {
  user_todat_latout = false;
}
Tom Aranda
  • 5,919
  • 11
  • 35
  • 51
Issac Nabil
  • 41
  • 1
  • 4
  • 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. – Tom Aranda Dec 16 '17 at 04:17
  • 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 :) – Issac Nabil Dec 22 '17 at 17:12
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.

qix
  • 7,228
  • 1
  • 55
  • 65
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;
}
android developer
  • 114,585
  • 152
  • 739
  • 1,270
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;
}
Kumar Santanu
  • 603
  • 1
  • 7
  • 14