Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Display Size in Inches in Android?

Tags:

android


I need for my Application the exact inch of a display. My current solution is:

double inch;
double x = Math.pow(widthPix/dm.xdpi,2);
double y = Math.pow(heigthPix/dm.ydpi,2);
double screenInches = Math.sqrt(x+y);

inch = screenInches;

inch = inch * 10;
inch = Math.round(inch);
inch = inch / 10;

Is there a better way to get the display inch? Current on my test device 4 inch it say 5.9 and that is wrong...

like image 758
ternes3 Avatar asked Oct 18 '13 08:10

ternes3


2 Answers

The following gave me a a result quite close to the specs:

    DisplayMetrics dm = getResources().getDisplayMetrics();

    double density = dm.density * 160;
    double x = Math.pow(dm.widthPixels / density, 2);
    double y = Math.pow(dm.heightPixels / density, 2);
    double screenInches = Math.sqrt(x + y);
    log.info("inches: {}", screenInches);

Output: inches: 4.589389937671455
Specs: Samsung Galaxy Nexus (720 x 1280 px, ~320 dpi, 4.65")

Please note, that dm.heightPixels (or dm.widthPixels depending on your orientatation) does not necessarily provide accurate information, since soft keys (as used in the Galaxy Nexus) are not added to the height (or width).

like image 159
Father Stack Avatar answered Oct 20 '22 06:10

Father Stack


Try this.... This will give you the exact size of the display..

static String getDisplaySize(Activity activity) {
    double x = 0, y = 0;
    int mWidthPixels, mHeightPixels;
    try {
        WindowManager windowManager = activity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        display.getMetrics(displayMetrics);
        Point realSize = new Point();
        Display.class.getMethod("getRealSize", Point.class).invoke(display, realSize);
        mWidthPixels = realSize.x;
        mHeightPixels = realSize.y;
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        x = Math.pow(mWidthPixels / dm.xdpi, 2);
        y = Math.pow(mHeightPixels / dm.ydpi, 2);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return String.format(Locale.US, "%.2f", Math.sqrt(x + y));
}
like image 6
AluthSoft Dark Avatar answered Oct 20 '22 04:10

AluthSoft Dark