83

Android defines screen sizes as Normal Large XLarge etc.

It automatically picks between static resources in appropriate folders. I need this data about the current device in my java code. The DisplayMetrics only gives information about the current device density. Nothing is available regarding screen size.

I did find the ScreenSize enum in grep code here However this does not seem available to me for 4.0 SDK. Is there a way to get this information?

swiftBoy
  • 35,607
  • 26
  • 136
  • 135
user1454356
  • 987
  • 1
  • 7
  • 5

13 Answers13

125

Copy and paste this code into your Activity and when it is executed it will Toast the device's screen size category.

int screenSize = getResources().getConfiguration().screenLayout &
        Configuration.SCREENLAYOUT_SIZE_MASK;

String toastMsg;
switch(screenSize) {
    case Configuration.SCREENLAYOUT_SIZE_LARGE:
        toastMsg = "Large screen";
        break;
    case Configuration.SCREENLAYOUT_SIZE_NORMAL:
        toastMsg = "Normal screen";
        break;
    case Configuration.SCREENLAYOUT_SIZE_SMALL:
        toastMsg = "Small screen";
        break;
    default:
        toastMsg = "Screen size is neither large, normal or small";
}
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
  • 18
    i used this above and run it different emulator like large,medium,small. but i get toast normal screen..how to solve it – Palaniraja Mar 01 '13 at 11:07
70
private static String getScreenResolution(Context context)
{
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;

    return "{" + width + "," + height + "}";
}
David
  • 37,109
  • 32
  • 120
  • 141
  • 3
    your code is giving result excluding soft touch buttons in bottom and status bar and toolbar in top @David – Umar Ata Jun 01 '18 at 09:08
  • Exactly what I wanted ! Works like a charm – Itoun Sep 18 '19 at 09:34
  • Thanks. This code works fine for me on android emulator phones and tablets. But when I rotate the tablet, the resolution numbers are not inverted instead the actual value is changes. But for phone it works fine. How can I solve this? – SAIFI369 Mar 18 '20 at 20:20
  • It's help me a lot. It's really helpful when you use animations in Android , and theLayout weight and Layout percentage are not use. – Abdullah Sheikh Aug 06 '21 at 01:27
4

I think it is a pretty straight forward simple piece of code!

public Map<String, Integer> deriveMetrics(Activity activity) {
    try {
        DisplayMetrics metrics = new DisplayMetrics();

        if (activity != null) {
            activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        }

        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("screenWidth", Integer.valueOf(metrics.widthPixels));
        map.put("screenHeight", Integer.valueOf(metrics.heightPixels));
        map.put("screenDensity", Integer.valueOf(metrics.densityDpi));

        return map;
    } catch (Exception err) {
        ; // just use zero values
        return null;
    }
}

This method now can be used anywhere independently. Wherever you want to get information about device screen do it as follows:

        Map<String, Integer> map = deriveMetrics2(this);
        map.get("screenWidth");
        map.get("screenHeight");
        map.get("screenDensity");

Hope this might be helpful to someone out there and may find it easier to use. If I need to re-correct or improve please don't hesitate to let me know! :-)

Cheers!!!

Randika Vishman
  • 7,983
  • 3
  • 57
  • 80
  • Thanks. This code works fine for me on android emulator phones and tablets. But when I rotate the tablet, the resolution numbers are not inverted instead the actual value is changes. But for phone it works fine. How can I solve this? – SAIFI369 Mar 18 '20 at 20:21
4
DisplayMetrics displayMetrics = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

int width = displayMetrics.widthPixels;

int height = displayMetrics.heightPixels;
  • Thanks. This code works fine for me on android emulator phones and tablets. But when I rotate the tablet, the resolution numbers are not inverted instead the actual value is changes. But for phone it works fine. How can I solve this? – SAIFI369 Mar 18 '20 at 20:21
4

Ways to get DisplayMetrics:

1.

val dm = activity.resources.displayMetrics
val dm = DisplayMetrics() 
activity.windowManager.defaultDisplay.getMetrics(dm)
  1. val dm = DisplayMetrics() val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager wm..defaultDisplay.getMetrics(dm)

then get

The screen density expressed as dots-per-inch. May be either DENSITY_LOW, DENSITY_MEDIUM, or DENSITY_HIGH

dm.densityDpi

The absolute height of the available display size in pixels.

dm.heightPixels

The absolute width of the available display size in pixels.

dm.widthPixels

The exact physical pixels per inch of the screen in the X dimension.

dm.xdpi

The exact physical pixels per inch of the screen in the Y dimension.

dm.ydpi

DisplayMetrics

iamanbansal
  • 2,412
  • 2
  • 12
  • 20
3

You can get display size in pixels using this code.

Display display = getWindowManager().getDefaultDisplay();
SizeUtils.SCREEN_WIDTH = display.getWidth();
SizeUtils.SCREEN_HEIGHT = display.getHeight();
Aqif Hamid
  • 3,511
  • 4
  • 25
  • 38
2

With decorations (including button bar):

private static String getScreenResolution(Context context) {
    DisplayMetrics metrics = new DisplayMetrics();
    ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRealMetrics(metrics);
    return "{" + metrics.widthPixels + "," + metrics.heightPixels + "}";
}

Without decorations:

private static String getScreenResolution(Context context) {
    DisplayMetrics metrics = new DisplayMetrics();
    ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
    return "{" + metrics.widthPixels + "," + metrics.heightPixels + "}";
}

The difference is the method getMetrics() vs getRealMetrics() of the Display class.

Julian Paul
  • 162
  • 1
  • 2
2

The code will give you the result in the following format: width x height

String displayResolution = getResources().getDisplayMetrics().widthPixels + "x" + getResources().getDisplayMetrics().heightPixels;
  • What if device that OP is using it not 1440x2560? Your answer should be more specific. Code may be good, but description will not be always valid. – Magiczne Oct 04 '20 at 12:02
1

simon-

Different screen sizes have different pixel densities. A 4 inch display on your phone could have more or less pixels then say a 26 inch TV. If Im understanding correctly he wants to detect which of the size groups the current screen is, small, normal, large, and extra large. The only thing I can think of is to detect the pixel density and use that to determine the actual size of the screen.

Kevin Brey
  • 1,233
  • 1
  • 12
  • 18
1

I need this for a couple of my apps and the following code was my solution to the problem. Just showing the code inside onCreate. This is a stand alone app to run on any device to return the screen info.

setContentView(R.layout.activity_main);
    txSize = (TextView) findViewById(R.id.tvSize);

    density = (TextView) findViewById(R.id.density);
    densityDpi = (TextView) findViewById(R.id.densityDpi);
    widthPixels = (TextView) findViewById(R.id.widthPixels);
    xdpi = (TextView) findViewById(R.id.xdpi);
    ydpi = (TextView) findViewById(R.id.ydpi);

    Configuration config = getResources().getConfiguration();

    if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
        Toast.makeText(this, "Large screen", Toast.LENGTH_LONG).show();
        txSize.setText("Large screen");
    } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
        Toast.makeText(this, "Normal sized screen", Toast.LENGTH_LONG)
                .show();
        txSize.setText("Normal sized screen");
    } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
        Toast.makeText(this, "Small sized screen", Toast.LENGTH_LONG)
                .show();
        txSize.setText("Small sized screen");
    } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
        Toast.makeText(this, "xLarge sized screen", Toast.LENGTH_LONG)
                .show();
        txSize.setText("Small sized screen");
    } else {
        Toast.makeText(this,
                "Screen size is neither large, normal or small",
                Toast.LENGTH_LONG).show();
        txSize.setText("Screen size is neither large, normal or small");
    }

    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);

    Log.i(TAG, "density :" + metrics.density);
    density.setText("density :" + metrics.density);

    Log.i(TAG, "D density :" + metrics.densityDpi);
    densityDpi.setText("densityDpi :" + metrics.densityDpi);

    Log.i(TAG, "width pix :" + metrics.widthPixels);
    widthPixels.setText("widthPixels :" + metrics.widthPixels);

    Log.i(TAG, "xdpi :" + metrics.xdpi);
    xdpi.setText("xdpi :" + metrics.xdpi);

    Log.i(TAG, "ydpi :" + metrics.ydpi);
    ydpi.setText("ydpi :" + metrics.ydpi);

And a simple XML file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/tvSize"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />
<TextView
    android:id="@+id/density"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />
<TextView
    android:id="@+id/densityDpi"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />
<TextView
    android:id="@+id/widthPixels"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />
<TextView
    android:id="@+id/xdpi"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />
<TextView
    android:id="@+id/ydpi"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

Eric Engel
  • 305
  • 4
  • 15
0

If you are in a non-activity i.e. Fragment, Adapter, Model class or any other java class that do not extends Activity simply getResources() will not work. You can use getActivity() in fragment or use context that you pass to the corresponding class.

mContext.getResources()

I would recommend making a class say Utils that will have method/Methods for the common work. The benefit for this is you can get desired result with single line of code anywhere in the app calling this method.

Inzimam Tariq IT
  • 6,548
  • 8
  • 42
  • 69
0

The algorithm below can be used to identify which category will be used for picking between the static resources and also caters for the newer XX and XXX high densities

    DisplayMetrics displayMetrics = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    mDensityDpi = displayMetrics.densityDpi;
    mDensity = displayMetrics.density;
    mDisplayWidth = displayMetrics.widthPixels;
    mDisplayHeight = displayMetrics.heightPixels;

    String densityStr = "Unknown";
    int difference, leastDifference = 9999;

    difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_LOW);
    if (difference < leastDifference) {
        leastDifference = difference;
        densityStr = "LOW";
    }

    difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_MEDIUM);
    if (difference < leastDifference) {
        leastDifference = difference;
        densityStr = "MEDIUM";
    }

    difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_HIGH);
    if (difference < leastDifference) {
        leastDifference = difference;
        densityStr = "HIGH";
    }

    difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_XHIGH);
    if (difference < leastDifference) {
        leastDifference = difference;
        densityStr = "XHIGH";
    }

    difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_XXHIGH);
    if (difference < leastDifference) {
        leastDifference = difference;
        densityStr = "XXHIGH";
    }

    difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_XXXHIGH);
    if (difference < leastDifference) {
        densityStr = "XXXHIGH";
    }

    Log.i(TAG, String.format("Display [h,w]: [%s,%s] Density: %s Density DPI: %s [%s]", mDisplayHeight, mDisplayWidth, mDensity, mDensityDpi, densityStr));
Alex Kon
  • 1
  • 1
0

Get screen resolution or screen size in Kotlin

fun getScreenResolution(context: Context): Pair<Int, Int> {
    try {
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = wm.defaultDisplay
        val metrics = DisplayMetrics()
        display.getMetrics(metrics)
        val width = metrics.widthPixels
        val height = metrics.heightPixels
        //Log.d(AppData.TAG, "screenSize: $width, $height")
        return Pair(width, height)

    } catch (error: Exception) {
        Log.d(AppData.TAG, "Error : autoCreateTable()", error)
    }

    return Pair(0, 0)
}
TOUSIF
  • 285
  • 5
  • 4