Get fullscreen width and height on android

187 Views Asked by At

I'm trying to get the screen size when using a fullscreen app on android. This is what I'm doing:

DisplayMetrics displayMetrics = new DisplayMetrics();
               
getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
float density = displayMetrics.density;

WIDTH = width/density;
HEIGHT = height/density;

My problem is that on some devices, I get a black border on the top and the screen extends at the bottom (there is a small offset). It doesn't look like a hardware problem as other apps on my phone run at fullscreen normally. Example screenshot

Is there anything I can do? Thanks

2

There are 2 best solutions below

0
Paul Kocian On BEST ANSWER

Ok I solved it by mixing some of the answers here on stackoverflow. This is what I did:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
  • I added this:
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
  • And this:
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

The only problem, as mentioned in this answer by @Cloverleaf was that I used some deprecated APIs. Now with this changes and by using the code for API 30 it works fine, screenshot.

7
Cloverleaf On

The method getRealMetrics is deprecated as of API 31, see here. Use this instead (for API 30+):

WindowMetrics metrics = this.getSystemService(WindowManager.class).getCurrentWindowMetrics();
int width = metrics.getBounds().width();
int height = metrics.getBounds().height();
float density = metrics.getDensity(); //This line even requires API 34, otherwise your method from above.