You can use the DisplayMetrics to get a whole bunch of information about the screen that your app is running on.
First, we create a DisplayMetrics metrics object:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int wwidth = displaymetrics.widthPixels;
This will return the absolute value of the width and the height in pixels, so 1280x720 for the Galaxy SIII, the Galaxy Nexus etc.
This isn't usually helpful on its own, as when we're working on Android devices, we usually prefer to work in density independent pixels, dip.
float scaleFactor = displaymetrics .density;
From this result, we can calculate the amount of density independent pixels there are for a certain height or width.
float widthDp = widthPixels / scaleFactor
float heightDp = heightPixels / scaleFactor
Using the above information, we know that if the smallest-width of the device is greater than 600dp, the device is a 7" tablet, if it's greater than 720dp, the device is a 10" tablet.
We can work out the smallest width using the min function of Math class, passing in the heightDp and the widthDp to return the smallestWidth.
float smallestWidth = Math.min(widthDp, heightDp);
if (smallestWidth > 720) {
//Device is a 10" tablet
}
else if (smallestWidth > 600) {
//Device is a 7" tablet
}
However, this doesn't always give you an exact match, especially when working with obscure tablets that might be misrepresenting their density as hdpi when it isn't, or that might only be 800 x 480 pixels yet still be on a 7" screen.
Further to these methods, if you ever need to know the exact dimensions of a device in inches, you can work that out too, using the metrics method for how many pixels there are per inch of the screen.
float widthDpi = displaymetrics .xdpi;
float heightDpi = displaymetrics .ydpi;
You can use the knowledge of how many pixels are in each inch of device and the amount of pixels in total to work out how many inches the device is.
float widthInches = widthPixels / widthDpi;
float heightInches = heightPixels / heightDpi;
This will return the height and width of the device in inches. This again isn't always that helpful for determining what type of device it is, as the advertised size of a device is the diagonal, all we have is the height and the width.
However, we also know that given the height of a triangle and the width, we can use the Pythagorean theorem to work out the length of the hypotenuse (In this case, the size of the screen diagonal).
//a² + b² = c²
//The size of the diagonal in inches is equal to the square root of the height in inches squared plus the width in inches squared.
double diagonalInches = Math.sqrt(
(widthInches * widthInches)
+ (heightInches * heightInches));
From this, we can work out whether the device is a tablet or not:
if (diagonalInches >= 10) {
//Device is a 10" tablet
}
else if (diagonalInches >= 7) {
//Device is a 7" tablet
}