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" />