改变程序中的默认自动旋转屏幕

程序中有一个开关按钮。我想改变或控制默认设置,用代码的方式实现自动旋转屏幕(Settings>Display>Auto rotate screen) 。
如何实现?

先判断是否打开:
int flag=Settings.System.getInt(context.getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0);
打开关闭,关闭打开:
Settings.System.putInt(context.getContentResolver(),Settings.System.ACCELEROMETER_ROTATION,flag==1?0:1);

还得在manifest里面设置
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="user"

并且要加上权限:
android.permission.WRITE_SETTINGS

在你的 activity 中加入:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//这是默认值
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

你可以使用下面的代码来禁止自动转向:

public static void setAutoOrientationEnabled(ContentResolver resolver, boolean enabled)
{
  Settings.System.putInt(resolver, Settings.System.ACCELEROMETER_ROTATION, enabled ? 1 : 0);
}