Search code examples
androidandroid-layoutorientation

How can I globally force screen orientation in Android?


There are a number of apps that are able to force screen rotation. They work even if an app explicitly wants to be viewed in another orientation. Right now I am disabling the accelerometer rotation system setting and setting my preferred orientation. An app can still override this.

Here is one of the apps that is able to override an app's requested orientation:

https://play.google.com/store/apps/details?id=nl.fameit.rotate&hl=en


Solution

  • This can be done by creating a hidden system dialog. Its kind of a hack but its crazy enough to work.

        wm = (WindowManager) content.getSystemService(Service.WINDOW_SERVICE);
    
        orientationChanger = new LinearLayout(content);
        orientationChanger.setClickable(false);
        orientationChanger.setFocusable(false);
        orientationChanger.setFocusableInTouchMode(false);
        orientationChanger.setLongClickable(false);
    
        orientationLayout = new WindowManager.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                windowType, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.RGBA_8888);
    
        wm.addView(orientationChanger, orientationLayout);
        orientationChanger.setVisibility(View.GONE);
    
        orientationLayout.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        wm.updateViewLayout(orientationChanger, orientationLayout);
        orientationChanger.setVisibility(View.VISIBLE);