Java tutorial
//package com.java2s; //License from project: Open Source License import android.app.Activity; import android.util.DisplayMetrics; import java.text.DecimalFormat; public class Main { private static DisplayMetrics dm; public static double getDPI(Activity activity) { return calculateDPI(getWidth(activity), getHeight(activity), Double.valueOf(new DecimalFormat("#.##").format(getScreenSize(activity)))); } public static double calculateDPI(int width, int height, double screenSize) { return Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)) / screenSize; } public static int getWidth(Activity activity) { if (dm == null) { dm = new DisplayMetrics(); } activity.getWindowManager().getDefaultDisplay().getMetrics(dm); return dm.widthPixels; } public static int getHeight(Activity activity) { if (dm == null) { dm = new DisplayMetrics(); } activity.getWindowManager().getDefaultDisplay().getMetrics(dm); return dm.heightPixels; } public static double getScreenSize(Activity activity) { if (dm == null) { dm = new DisplayMetrics(); } activity.getWindowManager().getDefaultDisplay().getMetrics(dm); double x = Math.pow(dm.widthPixels / dm.densityDpi, 2); double y = Math.pow(dm.heightPixels / dm.densityDpi, 2); return Math.sqrt(x + y); } }