Android gets screen height and width (excluding / including virtual keys), height of status bar

Keywords: Mobile Android

There are many inaccurate ways to get the width and height of the screen on the Internet. Here, I use my mobile phone as a test to summarize some accurate methods, so I have this article.
The height below refers to the length of the phone from top to bottom, and the width refers to the length from left to right.
1.Android gets screen height and width (excluding virtual keys)
Generally, we need to know the height without virtual keys, because no control layout can be suspended on the displayed virtual keys. The height and width obtained by this method are different when there is a virtual key or not, and the value obtained by this method is the height and width of the virtual key part not included.

WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        int height = outMetrics.heightPixels;

2.Android gets the screen height and width (including virtual buttons, that is, the real height and width of the mobile screen)
The values obtained below are consistent with and without virtual keys. Because the virtual buttons will only be available at the beginning of Android 4.4, here's a judgment

  WindowManager windowManager =
                (WindowManager) getApplication().getSystemService(Context.
                WINDOW_SERVICE);
        final Display display = windowManager.getDefaultDisplay();
        Point outPoint = new Point();
        if (Build.VERSION.SDK_INT >= 19) {
            // There may be virtual keys
            display.getRealSize(outPoint);
        } else {
            // No virtual key
            display.getSize(outPoint);
        }
        int mRealSizeWidth;//Real width of mobile screen
        int mRealSizeHeight;//Real height of mobile screen
        mRealSizeHeight = outPoint.y;
        mRealSizeWidth = outPoint.x;

3. Get status bar height
It can be called anywhere to get the height of the status bar, which is the only way that I know to call in the onCreate() method and get the height of the accurate status bar directly. Note that when the status bar is hidden, this method will also return the value when the status bar is displayed, and 0 will not be displayed.

public static int getStatusBarHeight() { 
int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", 
        "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
}

Posted by SleepyP on Thu, 02 Apr 2020 01:26:24 -0700