如何以编程方式获取设备 DPI?

How to get Device DPI programmatically?

如何以编程方式获取设备 DPI。我需要那个值,而不是像 HDPI 或 MDPI 这样的设备

    DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch(metrics.densityDpi){
     case DisplayMetrics.DENSITY_LOW:
                break;
     case DisplayMetrics.DENSITY_MEDIUM:
                 break;
     case DisplayMetrics.DENSITY_HIGH:
                 break;
}

此代码仅显示高或低,但我需要值

使用metrics.xdpimetrics.ydpi

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);

// will either be DENSITY_LOW, DENSITY_MEDIUM or DENSITY_HIGH
int dpiClassification = dm.densityDpi;

// these will return the actual dpi horizontally and vertically
 float xDpi = dm.xdpi;
 float yDpi = dm.ydpi;