获取Android设备屏幕大小

1.Java 代码

Android获取屏幕宽度与长度的五个方法 (taodudu.cc)  存在的问题 :获取到的数据 只是屏幕大小 没有包含系统导航栏的高度/宽度。

解决方法:使用 WindowMetrics

    public void getScreenParams(){
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
            WindowMetrics currentWindowMetrics = wm.getCurrentWindowMetrics();
            int width = currentWindowMetrics.getBounds().width();
            int height = currentWindowMetrics.getBounds().height();
            screenInfo.setText("屏幕分辨率为:"+width+"*"+height);
            Log.e(getClass().getName(),"screen width:"+width+"   screen height:"+height);
        }else {
            int width = wm.getDefaultDisplay().getWidth();
            int height = wm.getDefaultDisplay().getHeight();
            screenInfo.setText("屏幕分辨率为:"+width+"*"+height);
            Log.e(getClass().getName(),"screen width:"+width+"   screen height:"+height);
        }
//
//
//        DisplayMetrics dm = new DisplayMetrics();
//
//        getWindowManager().getDefaultDisplay().getMetrics(dm);
//        int mScreenWidth = dm.widthPixels;// 获取屏幕分辨率宽度
//        int mScreenHeight = dm.heightPixels;
//
//        Log.e(getClass().getName(),"screen width:"+mScreenWidth+"   screen height:"+mScreenHeight);
//
//        int mScreenWidth1  = getResources().getDisplayMetrics().widthPixels;
//
//        int mScreenHeight1 = getResources().getDisplayMetrics().heightPixels;
//
//        Log.e(getClass().getName(),"screen width:"+mScreenWidth1+"   screen height:"+mScreenHeight1);
    }

2.adb 命令

wm 命令 

adb shell wm
usage: wm [subcommand] [options]
       wm size [reset|WxH]
       wm density [reset|DENSITY]
       wm overscan [reset|LEFT,TOP,RIGHT,BOTTOM]

 如何从adb命令行获取Android设备的屏幕尺寸? | 码农家园 (codenong.com)

(331条消息) Android 11(Android R)状态栏高度获取_沙漠一只雕得儿得儿的博客-CSDN博客

3.获取导航栏高度

public static int getStatusBarHeight(Context context) {
 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        WindowMetrics windowMetrics = wm.getCurrentWindowMetrics();
        WindowInsets windowInsets = windowMetrics.getWindowInsets();
        Insets insets = windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.navigationBars() | WindowInsets.Type.displayCutout());
        return insets.bottom;
    }       
    
    ....
}

 

getInsetsIgnoringVisibility
posted @ 2023-05-05 16:38  xiaowang_lj  阅读(1567)  评论(0编辑  收藏  举报