Safe way to get Android status bar height across variety of APIs?

I have a code for finding the Android status bar which is:

    public static int getAndroidStatusBarHeight() {
#if UNITY_ANDROID && !UNITY_EDITOR

        AndroidJavaClass up = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject ca = up.GetStatic<AndroidJavaObject>("currentActivity");
        var windowManager = ca.Call<AndroidJavaObject>("getWindowManager");
        var wMetrics = windowManager.Call<AndroidJavaObject>("getCurrentWindowMetrics");
        var insets = wMetrics.Call<AndroidJavaObject>("getWindowInsets");

        return insets.Call<int>("getStableInsetTop");
#endif
        return 0;
    }

Does anyone know how low the API is that this will work on for Android?

ie. Would it only run on API 16+? or 20+? or 25+? Or 30+?

I just want to make sure all my methods are safe for all APIs so there are no crashes or errors. Is this a broadly safe method or is there another method I should use?

This is all just a googlefest in the online Android docs from Google, nothing whatsoever to do with Unity3D.

AndroidJavaClass and AndroidJavaObject are just conduits to the underlying OS.

    public static int getAndroidStatusBarHeight() {
        #if UNITY_ANDROID && !UNITY_EDITOR
  
                AndroidJavaClass up = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
                AndroidJavaObject ca = up.GetStatic<AndroidJavaObject>("currentActivity");
                var getWindow = ca.Call<AndroidJavaObject>("getWindow");
                var DecorView = getWindow.Call<AndroidJavaObject>("getDecorView");
                var insets = DecorView.Call<AndroidJavaObject>("getRootWindowInsets");
                return insets.Call<int>("getSystemWindowInsetTop");

        #else
                return 0;
        #endif
    }
1 Like