When i got the screen size of width and height, i used to use the WindowManager().getDefaultDisplay().getMetrics(metrics) before and this is the whole code below.
DisplayMetrics metrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(metrics);
usableHeight = metrics.heightPixels;
usableWidth = metrics.widthPixels;
But in Android 11, that getDefaultDisplay().getMetrics(metrics) is deprecated.
so i found `WindowInsets' and it worked well when the screen is being showing.
and it also worked well when the screen is from portrait to portrait or landscape to landscape.
but there is a problem. when i rotate the screen from portrait to landscape forcibly, WindowInsets can't get the accurate current size of the display.
in detail, it's 3 step.
1. Start the app.
2. As soon as the app start, the screen rotates from portrait to landscape forcibly.
3. WindowInsets can't get the Insets.right and Insets.left.
this the the whole code to get the display size.
private static int getDisplaySize(WindowManager wm, boolean wantWidth) {
int usableHeight = 0;
int usableWidth = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowMetrics metrics = wm.getCurrentWindowMetrics();
WindowInsets windowInsets = metrics.getWindowInsets();
Insets insets = windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.navigationBars() | WindowInsets.Type.displayCutout());
int insetsWidth = 0;
int insetsHeight = 0;
if (insets != null) {
insetsWidth = insets.right + insets.left;
insetsHeight = insets.top + insets.bottom;
}
Size realSize = new Size(0, 0);
if (metrics.getBounds() != null) {
Rect bounds = metrics.getBounds();
realSize = new Size(bounds.width() - insetsWidth, bounds.height() - insetsHeight);
}
usableWidth = realSize.getWidth();
usableHeight = realSize.getHeight();
} else {
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
usableHeight = metrics.heightPixels;
usableWidth = metrics.widthPixels;
}
return wantWidth ? usableWidth : usableHeight;
}
how can i get the Insets.right and Insets.left right after the screen rotating ??
Plus
I found some clues. please check these below.
when i start the app again, it gets correct values(width, height) but it couldn't when i start the app for the first time.
in the second time, i close the app and i touch home screen, and restart the app, it can't get correct width and height.
you can get correct width, height even though you close the app if you do not touch or drag your home screen.
so it operates weirdly.