How to check device natural (default) orientation on Android (i.e. get landscape for e.g., Motorola Charm or Flipout)

This method can help:--

public int getDeviceDefaultOrientation() {

    WindowManager windowManager =  (WindowManager) getSystemService(Context.WINDOW_SERVICE);

    Configuration config = getResources().getConfiguration();

    int rotation = windowManager.getDefaultDisplay().getRotation();

    if ( ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) &&
            config.orientation == Configuration.ORIENTATION_LANDSCAPE)
        || ((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) &&    
            config.orientation == Configuration.ORIENTATION_PORTRAIT)) {
      return Configuration.ORIENTATION_LANDSCAPE;
    } else { 
      return Configuration.ORIENTATION_PORTRAIT;
    }
}

Well, you can find out what current orientation is the way @Urboss said. You cannot get the layout (landscape/portrait) that way ofcourse, so you'll have to get the screen width/heigth to check if the current (be it changed or not, but you've checked that ;) ) position is landscape or portrait:

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    wPix = dm.widthPixels;
    hPix = dm.heightPixels;

(so if the rotation is 0 and you get landscape with above metrix, your device is default landscape. If the rotation is 90 degrees and you're portrait, the default is also landscape, and so on)


After hours and hours of trying to figure this out. It's not possible. However, the closest thing you can do is to set the orientation to "NOSENSOR"

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

What this will do is set your application to the natural orientation of the device. At this point you can get the height and width of the display using the DisplayMetrics class, and calculate if you are in landscape or portrait. After you then figure out if it's landscape or portrait, you can then do this

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_XXXXX);

Where XXXX is either LANDSCAPE or PORTRAIT.

The case where doing this may not work is if you have a slide out keyboard.

Tags:

Android