Search code examples
androidandroid-serviceorientationandroid-sensorsandroid-windowmanager

Android Get Device Orientation Using Sensons


I am developing application where in a service class I use WindowManager to inflate a view. So normally the view layout changes its orientation according to devices orientation, but when I open my camera application, the orientation does not changes. As shown in picture below:-

Figure 1

Figure 2

So how to change the views orientation as per devices orientation.

Thanks


Solution

  • There is a difference between determining whether your device's natural orientation is in landscape/portrait, or whether your app's resources are being rendered in landscape/portrait. It sounds like you want the former:

    int getNaturalOrientation() {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display defaultDisplay = windowManager.getDefaultDisplay();
        int rotation = defaultDisplay.getRotation();
        if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
            if (display.getDisplayHeight() >= display.getDisplayWidth()) {
                return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            }
            return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        } else {
            if (display.getDisplayHeight() < display.getDisplayWidth()) {
                return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            }
            return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        }
    }
    

    ~Inspired by code in Chromium src: https://chromium.googlesource.com/chromium/src/+/aca91b5d8a53d77e98021d560305a996864df5e8/content/public/android/javatests/src/org/chromium/content/browser/ScreenOrientationListenerTest.java