55

I need to know exactly how big the screen is on the device in real units of length so I can calculate the acceleration due to gravity in pixels per millisecond.

Is there a method somewhere in the Android API for this?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Nathan
  • 6,095
  • 10
  • 45
  • 54
  • 1
    If you're looking to do a one-off conversion (for instance for exporting sprites from Photoshop or designing your layout for a physical dimension), [here's a nifty converter](http://pixplicity.com/dp-px-converter/). – Paul Lammertsma Jul 01 '14 at 09:29

7 Answers7

93

Use the following:

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(mWidthPixels/dm.xdpi,2);
    double y = Math.pow(mHeightPixels/dm.ydpi,2);
    double screenInches = Math.sqrt(x+y);
    Log.d("debug","Screen inches : " + screenInches);

When mWidthPixels and mHeightPixels are taken from below code

private void setRealDeviceSizeInPixels()
{
    WindowManager windowManager = getWindowManager();
    Display display = windowManager.getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);


    // since SDK_INT = 1;
    mWidthPixels = displayMetrics.widthPixels;
    mHeightPixels = displayMetrics.heightPixels;

    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
    {
        try
        {
            mWidthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
            mHeightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
        }
        catch (Exception ignored)
        {
        }
    }

    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 17)
    {
        try
        {
            Point realSize = new Point();
            Display.class.getMethod("getRealSize", Point.class).invoke(display, realSize);
            mWidthPixels = realSize.x;
            mHeightPixels = realSize.y;
        }
        catch (Exception ignored)
        {
        }
    }

See this post for reference: Get screen dimensions in pixels

Community
  • 1
  • 1
Bghaak
  • 1,150
  • 14
  • 24
  • 10
    I have ~15 test devices and it fails on some of them, e.g it is not working on some models like Motorola Milestone or ZTE phones. – STeN Feb 06 '12 at 15:21
  • Do the failed devices models have custom ROM or the default one that the manufacturer provided? Perhaps it's something with the ROM? – AlikElzin-kilaka Apr 02 '12 at 11:49
  • 7
    Returned value isn't precise, because `getMetrics` (and `display.getWidht()`, or `display.getHeight()`) returns value that is available to your application (for example, it doesn't contains action bar height). So, on 1280x800 screen you can get value 1260x800 or 1280x780 and so on. – Dmitry Zaytsev Jun 25 '12 at 18:20
  • getWidth/getHeight are depricated now. You can use getSize instead, but I am not sure if they work correctly on all devices (see comment of STeN). – Michael Biermann Dec 09 '12 at 08:15
  • 3
    As STeN mentioned, this computation is incorrect for some devices. E.g., this code reports a 3" screen for a Droid Bionic, which actually has a 4.3" screen. The returned values for xdpi and ydpi on the Bionic are 368, 365 respectively, possibly due to the PenTile display or Motorola confusion. The actual DPI for this device is sqrt(960^2 + 540^2) / 4.3 = ~256 dpi. – Yojimbo Sep 11 '13 at 16:05
  • 2
    So, for the Droid Bionic and some other devices, you will get a more accurate screen size if you use the approximate DPI returned by DisplayMetrics.densityDpi rather than using xdpi/ydpi. – Yojimbo Sep 11 '13 at 16:18
  • @Bghaak please tell me any other alternative, coz above solution is giving wrong value in 9.3 inch tab – Nitin Misra Jan 08 '14 at 13:26
  • This code suggests me that Samsung S3 mini has 5.8" screen, while it has 4", and on Nexus 4 (LG) - it results in 4.4 while it has 4.7. Any better ways of doing this? – FDIM Mar 01 '14 at 23:17
  • 2
    Says my Samsung Galaxy Ace S5830I is 15 inches - clearly this is not the case! – slott Mar 04 '14 at 13:39
  • 1
    I looked into this and it seems the devices do not always have the correct DPI definition. So one solution is to check against the density and see if the difference is too great - and if it is then use the density ie. getResources().getDisplayMetrics().densityDpi – slott Mar 05 '14 at 06:33
  • @slott Do you have an example of what you mean? – Dave Nottage May 09 '17 at 03:16
  • this code gives result 6.88 inches on Android TV with 55 inches TV. – Anton Mar 15 '19 at 19:30
9

for getting the current size use Math.round at the end.

 DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(dm.widthPixels/dm.xdpi,2);
    double y = Math.pow(dm.heightPixels/dm.ydpi,2);
    double screenInches = Math.sqrt(x+y);
    Log.d("debug","Screen inches : " + screenInches);

screenInches=  (double)Math.round(screenInches * 10) / 10;
gilix
  • 545
  • 10
  • 14
4

android developers screen info.

use xdpi * widthPixels and ydpi * heightPixels might get you what you want i think.

gingerbreadboy
  • 7,386
  • 5
  • 36
  • 62
4

Following code snippet will help you to get Screen Size in Inches

public static double getScreenSizeInches(Activity activity){
    WindowManager windowManager = activity.getWindowManager();
    Display display = windowManager.getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);

    // since SDK_INT = 1;
    int mWidthPixels = displayMetrics.widthPixels;
    int mHeightPixels = displayMetrics.heightPixels;

    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) {
        try{
            mWidthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
            mHeightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
        } catch (Exception ignored) {}
    }

    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 17) {
        try {
            Point realSize = new Point();
            Display.class.getMethod("getRealSize", Point.class).invoke(display, realSize);
            mWidthPixels = realSize.x;
            mHeightPixels = realSize.y;
        } catch (Exception ignored) {}
    }

    DisplayMetrics dm = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(mWidthPixels / dm.xdpi, 2);
    double y = Math.pow(mHeightPixels / dm.ydpi, 2);
    return Math.sqrt(x + y);
}

Hope this help.

Pankaj Lilan
  • 4,245
  • 1
  • 29
  • 48
  • gives wrong result. I have emulator screen 4'65 the result is 4'59. it's better than the other solutions though. all of them gave me 4'3 – Desolator Apr 16 '18 at 03:31
1

I have tried most of the ways mentioned in the other answers, but those methods fail on particular devices. So here is bit of my contribution to solving this problem. The code is written in Kotlin

Get the DisplayMetrics object :

    val manager = mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val displayMetrics = DisplayMetrics()
    manager.getDefaultDisplay().getMetrics(displayMetrics)

Calculate the Screen width in inches as follows :

    val widthInDotPoints : Double = (displayMetrics.widthPixels * (160 * 1.0 /displayMetrics.densityDpi))
    val widthInInches : Double = width / displayMetrics.xdpi

Here, I have calculated the width of device in terms of dot points(dp) using widthPixels and then converted it to width in terms of inches. I have used 160 .i.e DisplayMetrics.DENSITY_MEDIUM as conversion factor to convert the widthPixels to widthInDotPoints.

Similarly, calculate the Screen Height in inches :

    val heightInDotPoints : Double = (displayMetrics.heightPixels * (160 * 1.0 /displayMetrics.densityDpi))
    val heightInInches : Double = height / displayMetrics.ydpi
Anish
  • 21
  • 1
0

I used this to get the real size

final DisplayMetrics metrics = new DisplayMetrics();
final WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    windowManager.getDefaultDisplay().getRealMetrics(metrics);
}
else {
    windowManager.getDefaultDisplay().getMetrics(metrics);
}
int realHeight = metrics.heightPixels; // This is real height
int realWidth = metrics.widthPixels; // This is real width
leegor
  • 472
  • 5
  • 15
-4

You need to use the screen density to calculate this.

Context.getResources().getDisplayMetrics().density

According to the documentation:

The logical density of the display. This is a scaling factor for the Density Independent Pixel unit, where one DIP is one pixel on an approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), providing the baseline of the system's display. Thus on a 160dpi screen this density value will be 1; on a 120 dpi screen it would be .75; etc.

This value does not exactly follow the real screen size (as given by xdpi and ydpi, but rather is used to scale the size of the overall UI in steps based on gross changes in the display dpi. For example, a 240x320 screen will have a density of 1 even if its width is 1.8", 1.3", etc. However, if the screen resolution is increased to 320x480 but the screen size remained 1.5"x2" then the density would be increased (probably to 1.5).

Community
  • 1
  • 1
CaseyB
  • 24,780
  • 14
  • 77
  • 112
  • 2
    Use xdpi and ydpi as described by the other poster. The density is deliberately not an absolute mapping to the physical screen size, but a more abstract unit that can be quantized to a small number of discreet values (currently 120dpi, 160dpi, 240dpi). – hackbod Feb 04 '10 at 08:51
  • This is a bad method and results in inaccurate values for both dpi and resolution. – grebulon Oct 01 '14 at 12:51