Monday, April 4, 2011

Disable screen rotation at runtime on Android

It's strange I found no ready solution in Net...

There are two sources that help me:
http://stackoverflow.com/questions/2795833/check-orientation-on-android-phone
http://www.anddev.org/rotate_screen_from_code_change_screen_orientation-t2687.html

Finally, the next code is really works (I tested it):


public class MyActivity extends Activity {

   private int mRuntimeOrientation;
   private boolean mDisableScreenRotation;

   protected int getScreenOrientation() {
      Display display = getWindowManager().getDefaultDisplay();
      int orientation = display.getOrientation();

      if (orientation == Configuration.ORIENTATION_UNDEFINED) {
         orientation = getResources().getConfiguration().orientation;

         if (orientation == Configuration.ORIENTATION_UNDEFINED) {
            if (display.getWidth() == display.getHeight())
               orientation = Configuration.ORIENTATION_SQUARE;
            else if(display.getWidth() < display.getHeight())

               orientation = Configuration.ORIENTATION_PORTRAIT;
            else
               orientation = Configuration.ORIENTATION_LANDSCAPE;
            }
         }
      return orientation;
   }

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      mRuntimeOrientation = this.getScreenOrientation();
   }

   @Override
   public void onConfigurationChanged(Configuration newConfig) {
      if (mDisableScreenRotation) {
         super.onConfigurationChanged(newConfig);
         this.setRequestedOrientation(mRuntimeOrientation);
      } else {
         mRuntimeOrientation = this.getScreenOrientation();
         super.onConfigurationChanged(newConfig);
      }
   }
}