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);
      }
   }
}

2 comments:

  1. i test your app,but the app also rocate screen when the app start,but when i roate screen third,your app is ok,why?

    ReplyDelete
  2. Look at code of the method MyActivity.getScreenOrientation(). It first looks at current screen orientation. If it is not defined then it looks for application configuration.
    You can try change first several lines like below to look application configuration first or remove this method and use Configuration.ORIENTATION_PORTRAIT to initialize mRuntimeOrientation field.

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

    if (orientation == Configuration.ORIENTATION_UNDEFINED) {
    orientation = display.getOrientation();
    ....

    ReplyDelete