How control screen orientation of Android device

15,119

Solution 1

@Override
    public void onCreate(Bundle savedInstanceState) {
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
}

or

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

Solution 2

Here are two approaches I know of:

Forcing screen orientation

If you want the orientation you set to override apps' own orientation preferences, follow the instructions in How can I globally force screen orientation in Android?.

Changing orientation non-forcefully

If you don't want the orientation you set to override apps' own orientation preferences, first ensure the phone's automatic rotation is turned off:

Settings.System.putInt(
    this.contentResolver,
    Settings.System.ACCELEROMETER_ROTATION,
    0 //0 means off, 1 means on
);

Then set the phone's user orientation:

Settings.System.putInt(
    getContentResolver(),
    Settings.System.USER_ROTATION,
    Surface.ROTATION_0 //Use any of the Surface.ROTATION_ constants
);

Don't forget to check the return values of putInt to ensure the change was successful.

Also, I think you need the following permission:

<uses-permission android:name="android.permission.WRITE_SETTINGS" />

Solution 3

Firstly, in android if you are not setting any orientation either through code or xml file then your app by default has orientation.

And if your requirement is that inspite of phone is in portrait/landscape mode and you require an single oreintation then you can lock it through code as follow in oncreate method::

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  //or
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
Share:
15,119
Admin
Author by

Admin

Updated on June 04, 2022

Comments