获取真实的density 密度因子

   double getdensity(Activity activity) {
        Point point = new Point();
        //这样获取的宽高准确,不是heightPixels
        if (Build.VERSION.SDK_INT > 16) {
            activity.getWindowManager().getDefaultDisplay().getRealSize(point);
        } else {
            activity.getWindowManager().getDefaultDisplay().getSize(point);
        }
        DisplayMetrics dm = getResources().getDisplayMetrics();
        double x = Math.pow(point.x / dm.xdpi, 2);//xdpi 屏幕X/Y轴上真正的物理PPI
        double y = Math.pow(point.y / dm.ydpi, 2);
        double screenInches = Math.sqrt(x + y);//尺寸
        double density = Math.sqrt(Math.pow(point.x, 2) + Math.pow(point.y, 2)) / screenInches / DisplayMetrics.DENSITY_MEDIUM;
        return density;
    }

如果通过API 获取的密度因子,通常被设备修改过,

   private static int getDeviceDensity() {
        // qemu.sf.lcd_density can be used to override ro.sf.lcd_density
        // when running in the emulator, allowing for dynamic configurations.
        // The reason for this is that ro.sf.lcd_density is write-once and is
        // set by the init process when it parses build.prop before anything else.
        return SystemProperties.getInt("qemu.sf.lcd_density",
                SystemProperties.getInt("ro.sf.lcd_density", DENSITY_DEFAULT));
    }

这个文件可以被设备制作商修改,使其参数好看


通常android UI高度设置,为了每个屏幕适配一样的高度,通常用这个密度因子算多少DP.