简体   繁体   中英

How to detect whether Android device is locked in portrait or landscape orientation

If in an Android device the auto rotate option is off - how can I check whether the user chose to lock the device in portrait or landscape mode?

I can't rely on the actual orientation that the device was in when the user changed the settings - in some devices (mostly phones) there is only portrait lock, which will be turned on even if the device is in landscape orientation.

I use this piece of code, but it returns only if the auto rotate is on or off, but not the actual lock orientation.

This for an app that is developed in Unity, so both Unity or Android native suggestions will be appreciated.

Thanks!

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

        return rotationOn == 1;
    }
}

如果您需要针对应用程序的特定方向(如肖像或横向),则可以使用android:screenOrientation在清单文件上进行设置。

To get the current orientation:

Kotlin

val display = (baseContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
val rotation = display.rotation

Java

Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();

Result could be:

Surface.ROTATION_0 
Surface.ROTATION_90 
Surface.ROTATION_180
Surface.ROTATION_270

90 and 270 for landscape

0 and 180 for portrait

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM