How can I globally force screen orientation in Android?

kagronick picture kagronick · Jan 29, 2013 · Viewed 34.6k times · Source

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

Answer

chrispaton picture chrispaton · Feb 13, 2013

I tried kagronick's answer but couldn't make it work. After messing around for a bit I eventually got it working using a system overlay window and removing the LayoutParams that I found were all unnecessary. Here's my eventual solution:

orientationChanger = new LinearLayout(this);
// Using TYPE_SYSTEM_OVERLAY is crucial to make your window appear on top
// You'll need the permission android.permission.SYSTEM_ALERT_WINDOW
WindowManager.LayoutParams orientationLayout = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, 0, PixelFormat.RGBA_8888);
// Use whatever constant you need for your desired rotation
orientationLayout.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR;

WindowManager wm = (WindowManager) this.getSystemService(Service.WINDOW_SERVICE);
wm.addView(orientationChanger, orientationLayout);
orientationChanger.setVisibility(View.VISIBLE);

You can see my success in the app I released based on this: Force Dock Rotation.