Android added notch support on API 28, but how to handle it on devices running API 27 (Honor 10, Huawei P20, etc.) ?
I was trying to use DisplayCutoutCompat<
I had similar issue, and had to use reflection to access what I need. My problem was that I had some calculations depending on screen size and while not accessing the notch space, the calculations were wrong and code didn't work well.
public static final String CLASS_DISPLAY_CUTOUT = "android.view.DisplayCutout";
public static final String METHOD_GET_DISPLAY_CUTOUT = "getDisplayCutout";
public static final String FIELD_GET_SAFE_INSET_TOP = "getSafeInsetTop";
public static final String FIELD_GET_SAFE_INSET_LEFT = "getSafeInsetLeft";
public static final String FIELD_GET_SAFE_INSET_RIGHT = "getSafeInsetRight";
public static final String FIELD_GET_SAFE_INSET_BOTTOM = "getSafeInsetBottom";
try {
WindowInsets windowInsets = activity.getWindow().getDecorView().getRootWindowInsets();
if (windowInsets == null) {
return;
}
Method method = WindowInsets.class.getMethod(METHOD_GET_DISPLAY_CUTOUT);
Object displayCutout = method.invoke(windowInsets);
if (displayCutout == null) {
return;
}
Class clz = Class.forName(CLASS_DISPLAY_CUTOUT);
int top = (int) clz.getMethod(FIELD_GET_SAFE_INSET_TOP).invoke(displayCutout);
int left = (int) clz.getMethod(FIELD_GET_SAFE_INSET_LEFT).invoke(displayCutout);
int right = (int) clz.getMethod(FIELD_GET_SAFE_INSET_RIGHT).invoke(displayCutout);
int bottom = (int) clz.getMethod(FIELD_GET_SAFE_INSET_BOTTOM).invoke(displayCutout);
Rect rect = new Rect(left, top, right, bottom);
} catch (Exception e) {
Log.e(TAG, "Error when getting display cutout size");
}