How to detect a screen cutout (notch) and get its height?

1.5k views Asked by At

I need to get the exact coordinates of a point relative to the screen regardless of the app window's dimensions or offsets/insets. The phone I'm developing on has a 1080x2280 resolution and android 9. I tried to find the screen dimensions using getDefaultDisply, but the notch height is getting subtracted from the screen:

// Testing with notch hidden; the screen is pushed down below it
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); // 1080x2062 (-notification bar height!)
getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics); // 1080x2192 (actual window height when notch is hidden)

How do I get the real resolution and the notch heigh when it's hidden?

2

There are 2 answers

0
Sri Kumaran Ramasubramaniam On

Solution I found was to use getRealMetrics to get the height of the screen.

getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics)

This calculates the height of the screen by including the height of the notch as well. Works for both Notched Mode ON/OFF also for devices without Notch

0
razz On

I found my own solution that works on rooted devices only (requires Shell library):

public static int getCutoutHeight() {
    CommandResult result = Shell.SU.run("dumpsys display | grep mCurrentDisplayRect");
    String output = result.getStdout();
    String regex = "^\\s+mCurrentDisplayRect=Rect\\(\\d+, (\\d+) - \\d+, \\d+\\)*$";
    if (output != null) {
        if (output.matches(regex)) {
            Pattern patt = Pattern.compile(regex);
            Matcher matcher = patt.matcher(output);
            if (matcher.find()) {
                return Integer.parseInt(matcher.group(1));
            }
        }
        else Log.e(TAG, "Unexpedted outptu: " + output);
    }
    else Log.e(TAG, "Command failed: " + result.getStderr());
    return 0;
}

Hopefully a better answer will come up soon.