Note:以下方案中的this均指Activity。
方案一
WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
//windows manager可以通过getSystemService获取,也可以在Activity中直接获取
//val wm = this.windowManager
DisplayMetrics dm = new DisplayMetrics();
wm.defaultDisplay.getMetrics(dm);
int width = dm.widthPixels; // 屏幕宽度(像素)
int height = dm.heightPixels; // 屏幕高度(像素)
float density = dm.density; // 屏幕密度(0.75 / 1.0 / 1.5)
int densityDpi = dm.densityDpi; // 屏幕密度dpi(120 / 160 / 240)
// 屏幕宽度算法:屏幕宽度(像素)/屏幕密度
int screenWidth = (int) (width / density); // 屏幕宽度(dp)
int screenHeight = (int) (height / density);// 屏幕高度(dp)
方案二
val wm = this.getSystemService(Context.WINDOW_SERVICE) as WindowManager
//windows manager可以通过getSystemService获取,也可以在Activity中直接获取
//val wm = this.windowManager
val outSize = Point()
wm.defaultDisplay.getSize(outSize)
val width2 = outSize.x
val height2 = outSize.y
方案三
val dm3 = this.resources.displayMetrics
val density3 = dm3.density
val width3 = dm3.widthPixels
val height3 = dm3.heightPixels