使用切换控制自动旋转?

Controlling Auto Rotation with toggle?

我想创建一个切换按钮,通过它我可以 enable/disable 自动旋转。我试过这个:

public void arclick(View view) {
        if (arclick.isChecked())
            android.provider.Settings.System.putInt(getContentResolver(),
                    android.provider.Settings.System.USER_ROTATION, 90);
        else
            android.provider.Settings.System.putInt(getContentResolver(),
                    android.provider.Settings.System.USER_ROTATION, 0);
    }

但它实际上不起作用。有任何想法吗?提前致谢!!! P.S: 所选方向应应用于整个操作系统,而不仅仅是应用程序。

根据开发者文档:

USER_ROTATION : Default screen rotation when no other policy applies. When ACCELEROMETER_ROTATION is zero and no on-screen Activity expresses a preference, this rotation value will be used. Must be one of the Surface rotation constants.

在使用USER_ROTATION之前,您需要将ACCELEROMETER_ROTATION设置为0。 喜欢:

android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.ACCELEROMETER_ROTATION, 0); 
if (arclick.isChecked())
    android.provider.Settings.System.putInt(getContentResolver(),
            android.provider.Settings.System.USER_ROTATION, Surface.ROTATION_90);
else
    android.provider.Settings.System.putInt(getContentResolver(),
            android.provider.Settings.System.USER_ROTATION, Surface.ROTATION_0);

并且不要使用值 90,使用 Surface。ROTATION_90(其值为 1 而不是 90)。

如果您想禁用旋转功能,请使用:

if(disable)
   android.provider.Settings.System.putInt(getContentResolver(),
   android.provider.Settings.System.ACCELEROMETER_ROTATION, 0); 
else //enable
   android.provider.Settings.System.putInt(getContentResolver(),
   android.provider.Settings.System.ACCELEROMETER_ROTATION, 1);