import android.os.Build;
static int screenTopMargin = 0; static int screenBottomMargin = 0;
@Override protected void onCreate(Bundle savedInstanceState) {
.......
if (Build.VERSION.SDK_INT >= 28) { getWindow().getDecorView().setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() { @Override public WindowInsets onApplyWindowInsets(View view, WindowInsets windowInsets) { Log.e("notch", "onApplyWindowInsets"); if(windowInsets == null){ return windowInsets; } DisplayCutout cutout = windowInsets.getDisplayCutout(); if (cutout == null) { Log.e("notch", "cutout==null, is not notch screen");//通过cutout是否为null判断是否刘海屏手机 } else { List<Rect> rects = cutout.getBoundingRects(); if (rects == null || rects.size() == 0) { Log.e("notch", "rects==null || rects.size()==0, is not notch screen"); } else { Log.e("notch", "rect size:" + rects.size());//注意:刘海的数量可以是多个 for (Rect rect : rects) { Log.e("notch", "cutout.getSafeInsetTop():" + cutout.getSafeInsetTop() + ", cutout.getSafeInsetBottom():" + cutout.getSafeInsetBottom() + ", cutout.getSafeInsetLeft():" + cutout.getSafeInsetLeft() + ", cutout.getSafeInsetRight():" + cutout.getSafeInsetRight() + ", cutout.rects:" + rect ); } screenTopMargin = cutout.getSafeInsetTop(); screenBottomMargin = cutout.getSafeInsetBottom(); } } return windowInsets; } }); }else { screenTopMargin = this.getStatusBarHeight(this.getResources()); screenBottomMargin = 0; }
}
public static int getStatusBarHeight(Resources resources) { int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android"); int height = resources.getDimensionPixelSize(resourceId); return height; }
public static int getScreenTopMargin() { return screenTopMargin; } public static int getScreenBottomMargin() { return screenBottomMargin; }