Search Unity

Lock auto rotation on Android doesn't work

Discussion in 'Android' started by swifter14, Mar 8, 2020.

  1. swifter14

    swifter14

    Joined:
    Mar 2, 2017
    Posts:
    165
    My orientation mode is set to Auto Rotation, users can play in Landscape or portrait mode.

    The problem is when the user locks rotation on their device (lock button on android settings) when I rotate the phone, the app is still rotating, why isn't it locked it like in other apps?

    I tried an old solution, but it doesn't work-

    void OnApplicationFocus(bool haveFocus)
    {
    if (haveFocus) ToggleAutoRotation();
    }

    static void ToggleAutoRotation()
    {
    autoRotationOn = DeviceAutoRotationIsOn();
    Screen.autorotateToPortrait = autoRotationOn;
    Screen.autorotateToPortraitUpsideDown = autoRotationOn;
    Screen.autorotateToLandscapeLeft = autoRotationOn;
    Screen.autorotateToLandscapeRight = autoRotationOn;
    Screen.orientation = ScreenOrientation.AutoRotation;
    }

    static bool DeviceAutoRotationIsOn()
    {
    #if UNITY_ANDROID && !UNITY_EDITOR
    using (var actClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
    {
    var context = actClass.GetStatic<AndroidJavaObject>("currentActivity");
    AndroidJavaClass systemGlobal = new AndroidJavaClass("android.provider.Settings$System");
    var rotationOn = systemGlobal.CallStatic<int>("getInt", context.Call<AndroidJavaObject>("getContentResolver"), "accelerometer_rotation");

    return rotationOn==1;
    }
    #endif
    return true;
    }
     
  2. eldelnacho

    eldelnacho

    Joined:
    May 19, 2021
    Posts:
    2
    I'm also interested.