628

How can I get the screen width and height and use this value in:

@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
    Log.e(TAG, "onMeasure" + widthSpecId);
    setMeasuredDimension(SCREEN_WIDTH, SCREEN_HEIGHT - 
        game.findViewById(R.id.flag).getHeight());
}
0xCursor
  • 2,242
  • 4
  • 15
  • 33
rebel_UA
  • 6,525
  • 3
  • 21
  • 19
  • 2
    see: http://stackoverflow.com/questions/1016896/android-how-to-get-screen-dimensions – Will Tate Jan 20 '11 at 03:18
  • 2
    Does this answer your question? [How to get screen dimensions as pixels in Android](https://stackoverflow.com/questions/1016896/how-to-get-screen-dimensions-as-pixels-in-android) – AdamHurwitz Aug 20 '20 at 00:24
  • the update correct answer https://stackoverflow.com/a/67691009/4797289 – Rasoul Miri May 25 '21 at 15:24

36 Answers36

1217

Using this code, you can get the runtime display's width & height:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;

In a view you need to do something like this:

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

In some scenarios, where devices have a navigation bar, you have to check at runtime:

public boolean showNavigationBar(Resources resources)
{
    int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
    return id > 0 && resources.getBoolean(id);
}

If the device has a navigation bar, then count its height:

private int getNavigationBarHeight() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight)
            return realHeight - usableHeight;
        else
            return 0;
    }
    return 0;
}

So the final height of the device is:

int height = displayMetrics.heightPixels + getNavigationBarHeight();
0xCursor
  • 2,242
  • 4
  • 15
  • 33
Parag Chauhan
  • 35,760
  • 13
  • 86
  • 95
  • 41
    Are the width and height swapped if the device is rotated? – Madeyedexter Nov 28 '16 at 06:51
  • 16
    @Madeyedexter yes it will. – Parag Chauhan Nov 28 '16 at 07:08
  • This doesn't work in a constraint layout, for some reason it crashes onMeasure without a message – David Aleksanyan Dec 05 '17 at 08:51
  • 1
    But you can no longer assume you are running on the default display. – satur9nine Jun 05 '18 at 22:30
  • 7
    or just simply use - getResources().getDisplayMetrics().heightPixels / getResources().getDisplayMetrics().widthPixels – Alex Jun 27 '18 at 17:09
  • @satur9nine because of running on Chrome OS, right? – EpicPandaForce Jul 09 '18 at 15:06
  • 1
    @EpicPandaForce actually I was thinking of Android Oreo which allows launching an activity on another display, see the following: https://developer.android.com/reference/android/app/ActivityOptions.html#setLaunchDisplayId(int) – satur9nine Jul 10 '18 at 22:31
  • This will also cause trouble with Foldables – EpicPandaForce Nov 12 '18 at 09:30
  • @EpicPandaForce can you please share in details what issues are you facing – Parag Chauhan Nov 12 '18 at 14:29
  • I'm doing this and getting slightly results: On a Moto X4 it returns the correct width (1080) but the returned height is wrong. It returns 1776, even though the device's specs quote 1920. I'm yet to find an api that returns the correct result. Maybe it is excluding the action bar and/or the buttons? – Tyler Mar 19 '19 at 21:55
  • @Madeyedexter when device rotates then height will be width & width will be height. – Ahamadullah Saikat Sep 12 '19 at 18:23
  • Hi @ParagChauhan, I failed to get actual screen width in some android devices running on OS versions 8.1 and 9. The calculated width is less than the actual width. What might be the problem? – Avik Chowdhury Apr 16 '20 at 23:29
  • There is a warning: Method invocation 'getDefaultDisplay' may produce 'NullPointerException' – activity May 19 '20 at 14:44
  • 17
    getDefaultDisplay() and getMetrics are deprecated – Greelings Aug 14 '20 at 07:55
  • By the way guys I think this solution needs modification as Display Apis are now deprecated in Api level 31. – Shivam Yadav Aug 02 '22 at 10:28
  • This is an outdated answer and it (and many of the other answers here) will get **window** width and height. Not screen width and height. So there may be a small or large discrepancy depending on the app, mode, and device. – Trevor Mar 30 '23 at 22:10
  • What's a navigation bar? Is that the bottom bar with three buttons? If so, why didn't you mention ActionBar (Toolbar)? – bighugedev Aug 04 '23 at 18:10
387

There is a very simple answer and without pass context

public static int getScreenWidth() {
    return Resources.getSystem().getDisplayMetrics().widthPixels;
}

public static int getScreenHeight() {
    return Resources.getSystem().getDisplayMetrics().heightPixels;
}

Note: if you want the height include navigation bar, use method below

WindowManager windowManager =
        (WindowManager) BaseApplication.getApplication().getSystemService(Context.WINDOW_SERVICE);
    final Display display = windowManager.getDefaultDisplay();
    Point outPoint = new Point();
    if (Build.VERSION.SDK_INT >= 19) {
        // include navigation bar
        display.getRealSize(outPoint);
    } else {
        // exclude navigation bar
        display.getSize(outPoint);
    }
    if (outPoint.y > outPoint.x) {
        mRealSizeHeight = outPoint.y;
        mRealSizeWidth = outPoint.x;
    } else {
        mRealSizeHeight = outPoint.x;
        mRealSizeWidth = outPoint.y;
    }
weigan
  • 4,625
  • 1
  • 13
  • 14
47

Just to update the answer by parag and SpK to align with current SDK backward compatibility from deprecated methods:

int Measuredwidth = 0;  
int Measuredheight = 0;  
Point size = new Point();
WindowManager w = getWindowManager();

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)    {
    w.getDefaultDisplay().getSize(size);
    Measuredwidth = size.x;
    Measuredheight = size.y; 
}else{
    Display d = w.getDefaultDisplay(); 
    Measuredwidth = d.getWidth(); 
    Measuredheight = d.getHeight(); 
}
dakshbhatt21
  • 3,558
  • 3
  • 31
  • 40
digiphd
  • 2,319
  • 3
  • 23
  • 22
  • 7
    @digiphd wouldn't Parang's code work on all API versions? All methods were introduced before API level 8 and I didn't find them deprecated at the android dev site. – Sufian May 22 '13 at 12:52
  • @Sufian I had trouble getting non-0 return values from the `getSize` implementation on a Samsung Galaxy Mini (API 10) but the deprecated methods in this answer return correctly. So this is useful for older versions of Android. – Damien Diehl Aug 09 '16 at 18:44
  • @Sufian can we set new dimension to screen width and height? – Srishti Roy Jan 18 '18 at 05:39
  • 1
    this is depreciated now :( – cegprakash Dec 30 '18 at 12:10
32

Why not

DisplayMetrics displaymetrics = getResources().getDisplayMetrics();

Then use

displayMetrics.widthPixels

and

displayMetrics.heightPixels
snipsnipsnip
  • 2,268
  • 2
  • 33
  • 34
wangqi060934
  • 1,552
  • 16
  • 23
30

It’s very easy to get in Android:

int width  = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Ness Tyagi
  • 2,008
  • 24
  • 18
  • 2
    this returns 0 on an emulator – jonadv Feb 09 '20 at 20:39
  • it won't give you the real screen size on most devices but just the area without window insets. I try it on a Google Pixel 4a and i get 2138px as height instead of the real one of 2340px. You need to add WindowInsets of system bars too – backspace83 Apr 14 '23 at 11:02
26

You can get width and height from context

java:

  int width= context.getResources().getDisplayMetrics().widthPixels;
  int height= context.getResources().getDisplayMetrics().heightPixels;

kotlin

    val width: Int = context.resources.displayMetrics.widthPixels
    val height: Int = context.resources.displayMetrics.heightPixels
Rasoul Miri
  • 11,234
  • 1
  • 68
  • 78
22

Kotlin Version via Extension Property

If you want to know the size of the screen in pixels as well as dp, using these extension properties really helps:


DimensionUtils.kt

import android.content.Context
import android.content.res.Resources
import android.graphics.Rect
import android.graphics.RectF
import android.os.Build
import android.util.DisplayMetrics
import android.view.WindowManager
import kotlin.math.roundToInt

/**
 * @author aminography
 */

private val displayMetrics: DisplayMetrics by lazy { Resources.getSystem().displayMetrics }

/**
 * Returns boundary of the screen in pixels (px).
 */
val screenRectPx: Rect
    get() = displayMetrics.run { Rect(0, 0, widthPixels, heightPixels) }

/**
 * Returns boundary of the screen in density independent pixels (dp).
 */
val screenRectDp: RectF
    get() = screenRectPx.run { RectF(0f, 0f, right.px2dp, bottom.px2dp) }

/**
 * Returns boundary of the physical screen including system decor elements (if any) like navigation
 * bar in pixels (px).
 */
val Context.physicalScreenRectPx: Rect
    get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        (applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager)
            .run { DisplayMetrics().also { defaultDisplay.getRealMetrics(it) } }
            .run { Rect(0, 0, widthPixels, heightPixels) }
    } else screenRectPx

/**
 * Returns boundary of the physical screen including system decor elements (if any) like navigation
 * bar in density independent pixels (dp).
 */
val Context.physicalScreenRectDp: RectF
    get() = physicalScreenRectPx.run { RectF(0f, 0f, right.px2dp, bottom.px2dp) }

/**
 * Converts any given number from pixels (px) into density independent pixels (dp).
 */
val Number.px2dp: Float
    get() = this.toFloat() / displayMetrics.density

/**
 * Converts any given number from density independent pixels (dp) into pixels (px).
 */
val Number.dp2px: Int
    get() = (this.toFloat() * displayMetrics.density).roundToInt()


Usage:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val widthPx = screenRectPx.width()
        val heightPx = screenRectPx.height()
        println("[PX] screen width: $widthPx , height: $heightPx")

        val widthDp = screenRectDp.width()
        val heightDp = screenRectDp.height()
        println("[DP] screen width: $widthDp , height: $heightDp")

        println()
        
        val physicalWidthPx = physicalScreenRectPx.width()
        val physicalHeightPx = physicalScreenRectPx.height()
        println("[PX] physical screen width: $physicalWidthPx , height: $physicalHeightPx")

        val physicalWidthDp = physicalScreenRectDp.width()
        val physicalHeightDp = physicalScreenRectDp.height()
        println("[DP] physical screen width: $physicalWidthDp , height: $physicalHeightDp")
    }
}

Result:

When the device is in portrait orientation:

[PX] screen width: 1440 , height: 2392
[DP] screen width: 360.0 , height: 598.0

[PX] physical screen width: 1440 , height: 2560
[DP] physical screen width: 360.0 , height: 640.0

When the device is in landscape orientation:

[PX] screen width: 2392 , height: 1440
[DP] screen width: 598.0 , height: 360.0

[PX] physical screen width: 2560 , height: 1440
[DP] physical screen width: 640.0 , height: 360.0
aminography
  • 21,986
  • 13
  • 70
  • 74
  • 1
    This code fails to take into account the height of the navigation bar. – Johann Apr 03 '21 at 06:29
  • 1
    @AndroidDev: Thank you for reporting the issue. Please use `Context.physicalScreenRectPx` and `Context.physicalScreenRectDp` to get the real dimension of the screen. – aminography Apr 03 '21 at 07:24
15

Some methods, applicable for retrieving screen size, are deprecated in API Level 31, including Display.getRealMetrics() and Display.getRealSize(). Starting from API Level 30 we can use WindowManager#getCurrentWindowMetrics(). The clean way to get screen size is to create some Compat class, e.g.:

object ScreenMetricsCompat {
    private val api: Api =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ApiLevel30()
        else Api()

    /**
     * Returns screen size in pixels.
     */
    fun getScreenSize(context: Context): Size = api.getScreenSize(context)

    @Suppress("DEPRECATION")
    private open class Api {
        open fun getScreenSize(context: Context): Size {
            val display = context.getSystemService(WindowManager::class.java).defaultDisplay
            val metrics = if (display != null) {
                DisplayMetrics().also { display.getRealMetrics(it) }
            } else {
                Resources.getSystem().displayMetrics
            }
            return Size(metrics.widthPixels, metrics.heightPixels)
        }
    }

    @RequiresApi(Build.VERSION_CODES.R)
    private class ApiLevel30 : Api() {
        override fun getScreenSize(context: Context): Size {
            val metrics: WindowMetrics = context.getSystemService(WindowManager::class.java).currentWindowMetrics
            return Size(metrics.bounds.width(), metrics.bounds.height())
        }
    }
}

Calling ScreenMetricsCompat.getScreenSize(this).height in Activity we can get a screen height.

Sergio
  • 27,326
  • 8
  • 128
  • 149
  • In class Api you can use `ContextCompat.getSystemService(context, WindowManager::class.java)?.defaultDisplay` not `context.getSystemService(WindowManager::class.java).defaultDisplay` to target APIs less than 23 safely – Islam Khaled Jun 15 '22 at 17:40
14

Try below code :-

1.

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

2.

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated

or

int width = getWindowManager().getDefaultDisplay().getWidth(); 
int height = getWindowManager().getDefaultDisplay().getHeight();

3.

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

metrics.heightPixels;
metrics.widthPixels;
duggu
  • 37,851
  • 12
  • 116
  • 113
12

I suggest you create extension functions.

/**
 * Return the width and height of the screen
 */
val Context.screenWidth: Int
  get() = resources.displayMetrics.widthPixels

val Context.screenHeight: Int
  get() = resources.displayMetrics.heightPixels

/**
 * Pixel and Dp Conversion
 */
val Float.toPx get() = this * Resources.getSystem().displayMetrics.density
val Float.toDp get() = this / Resources.getSystem().displayMetrics.density

val Int.toPx get() = (this * Resources.getSystem().displayMetrics.density).toInt()
val Int.toDp get() = (this / Resources.getSystem().displayMetrics.density).toInt()
Mattia Ferigutti
  • 2,608
  • 1
  • 18
  • 22
10
DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
int widthPixels = lDisplayMetrics.widthPixels;
int heightPixels = lDisplayMetrics.heightPixels;
Micer
  • 8,731
  • 3
  • 79
  • 73
Shubham
  • 521
  • 4
  • 11
9

None of the answers here work correctly for Chrome OS multiple displays, or soon-to-come Foldables.

When looking for the current configuration, always use the configuration from your current activity in getResources().getConfiguration(). Do not use the configuration from your background activity or the one from the system resource. The background activity does not have a size, and the system's configuration may contain multiple windows with conflicting sizes and orientations, so no usable data can be extracted.

So the answer is

val config = context.getResources().getConfiguration()
val (screenWidthPx, screenHeightPx) = config.screenWidthDp.dp to config.screenHeightDp.dp
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
9

As getMetrics and getRealMetrics are deprecated, Google recommends to determine the screen width and height as follows:

WindowMetrics windowMetrics = getActivity().getWindowManager().getMaximumWindowMetrics();
Rect bounds = windowMetrics.getBounds();
int widthPixels = bounds.width();
int heightPixels = bounds.height();

However, I've figured out another methode that gives me the same results:

Configuration configuration = mContext.getResources().getConfiguration();
Display.Mode mode = display.getMode();
int widthPixels = mode.getPhysicalWidth();
int heightPixels = mode.getPhysicalHeight();
Patrick
  • 136
  • 2
  • 9
8

For kotlin user's

fun Activity.displayMetrics(): DisplayMetrics {
   val displayMetrics = DisplayMetrics()
   windowManager.defaultDisplay.getMetrics(displayMetrics)
   return displayMetrics
}

And in Activity you could use it like

     resources.displayMetrics.let { displayMetrics ->
        val height = displayMetrics.heightPixels
        val width = displayMetrics.widthPixels
    }

Or in fragment

    activity?.displayMetrics()?.run {
        val height = heightPixels
        val width = widthPixels
    }
Silvia H
  • 8,097
  • 7
  • 30
  • 33
Ali mohammadi
  • 1,839
  • 26
  • 27
7

Full way to do it, that returns the true resolution (including when the user has changed the resolution) is to use "getRealSize".

I've noticed that all other available functions, including the ones the docs say to use instead of this - have some cases that the result is smaller.

Here's the code to do it:

            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Point size = new Point();
            wm.getDefaultDisplay().getRealSize(size);
            final int width = size.x, height = size.y;

And since this can change on different orientation, here's a solution (in Kotlin), to get it right no matter the orientation:

/**
 * returns the natural orientation of the device: Configuration.ORIENTATION_LANDSCAPE or Configuration.ORIENTATION_PORTRAIT .<br></br>
 * The result should be consistent no matter the orientation of the device
 */
@JvmStatic
fun getScreenNaturalOrientation(context: Context): Int {
    //based on : http://stackoverflow.com/a/9888357/878126
    val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val config = context.resources.configuration
    val rotation = windowManager.defaultDisplay.rotation
    return if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && config.orientation == Configuration.ORIENTATION_LANDSCAPE || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && config.orientation == Configuration.ORIENTATION_PORTRAIT)
        Configuration.ORIENTATION_LANDSCAPE
    else
        Configuration.ORIENTATION_PORTRAIT
}

/**
 * returns the natural screen size (in pixels). The result should be consistent no matter the orientation of the device
 */
@JvmStatic
fun getScreenNaturalSize(context: Context): Point {
    val screenNaturalOrientation = getScreenNaturalOrientation(context)
    val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val point = Point()
    wm.defaultDisplay.getRealSize(point)
    val currentOrientation = context.resources.configuration.orientation
    if (currentOrientation == screenNaturalOrientation)
        return point
    else return Point(point.y, point.x)
}
android developer
  • 114,585
  • 152
  • 739
  • 1,270
6
DisplayMetrics dimension = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dimension);
        int width = dimension.widthPixels;
        int height = dimension.heightPixels;
Cristiana Chavez
  • 11,349
  • 5
  • 55
  • 54
6

As an android official document said for the default display use Context#getDisplay() because this method was deprecated in API level 30.

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

This code given below is in kotlin and is written accodring to the latest version of Android help you determine width and height:

fun getWidth(context: Context): Int {
    var width:Int = 0
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        val displayMetrics = DisplayMetrics()
        val display: Display? = context.getDisplay()
        display!!.getRealMetrics(displayMetrics)
        return displayMetrics.widthPixels
    }else{
        val displayMetrics = DisplayMetrics()
        this.windowManager.defaultDisplay.getMetrics(displayMetrics)
        width = displayMetrics.widthPixels
        return width
    }
}

fun getHeight(context: Context): Int {
    var height: Int = 0
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        val displayMetrics = DisplayMetrics()
        val display = context.display
        display!!.getRealMetrics(displayMetrics)
        return displayMetrics.heightPixels
    }else {
        val displayMetrics = DisplayMetrics()
        this.windowManager.defaultDisplay.getMetrics(displayMetrics)
        height = displayMetrics.heightPixels
        return height
    }
}
Mohit Yadav
  • 158
  • 3
  • 11
  • 1
    Can you give a complete example for this – dilshan Sep 22 '20 at 03:13
  • 1
    u can copy the code and call the functions like `var one= getHeight(this)` and the value of the display's height will be stored in the variable one as the functions return the height and width values when called. – Mohit Yadav Sep 22 '20 at 04:30
6
fun Activity.getRealScreenSize(): Pair<Int, Int> { //<width, height>
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
    val size = Point()
    display?.getRealSize(size)
    Pair(size.x, size.y)
} else {
    val size = Point()
    windowManager.defaultDisplay.getRealSize(size)
    Pair(size.x, size.y)

}}

This is an extension function and you can use in your activity in this way:

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val pair = getRealScreenSize()
    pair.first //to get width
    pair.second //to get height
}
DevWM
  • 114
  • 1
  • 6
5

Get the value of screen width and height.

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
Pang
  • 9,564
  • 146
  • 81
  • 122
Anil Singhania
  • 785
  • 10
  • 9
5

After trying lots of versions above, I figured out an answer in Kotlin. It accurately returns the resolutions that are advertised for the devices. Please let me know if this does not work on older devices--I only have relatively new ones at the moment.

This solution uses no deprecated functions (as of Jan 2023).

private fun getScreenHeight() : Int {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        val windowMetrics = windowManager.currentWindowMetrics
        val rect = windowMetrics.bounds
        rect.bottom
    } else {
        resources.displayMetrics.heightPixels
    }
}
SMBiggs
  • 11,034
  • 6
  • 68
  • 83
  • This gave me 2030 but actual is 2160. Android 9 – kallis Jun 10 '23 at 09:24
  • @kallis Really? Which device are you using? I'd like to chase this down and figure out the details. It's a shame that something so basic has always been such a pain on Android. – SMBiggs Jun 30 '23 at 12:43
  • The device is Redmi Note 5 pro – kallis Jun 30 '23 at 13:14
  • That looks like a nice phone. But unfortunately I don't have access to it or anything similar. Do any of the other techniques listed above give you the correct screen height? To be off by 130 pixels feels like there is some navigation/status/app bar that is not being calculated. Hmmm. – SMBiggs Jun 30 '23 at 20:19
  • 1
    I ended up using `val outPoint = Point()` `view.display.getRealSize(outPoint)` . It is working consistently over all device. I took this from google's github project that was last updated on 17 Apr, but the doc says this method is deprecated. Maybe they are not even sure about themselves. – kallis Jun 30 '23 at 23:18
  • Glad that `getRealSize()` still works on your device. Hope this helps others. – SMBiggs Jul 02 '23 at 16:46
4
Display display = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int mWidthScreen = display.getWidth();
int mHeightScreen = display.getHeight();
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Rahul Yadav
  • 143
  • 6
4
public class DisplayInfo {
    int screen_height=0, screen_width=0;
    WindowManager wm;
    DisplayMetrics displaymetrics;

    DisplayInfo(Context context) {
        getdisplayheightWidth(context);
    }

    void getdisplayheightWidth(Context context) {
        wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        displaymetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displaymetrics);
        screen_height = displaymetrics.heightPixels;
        screen_width = displaymetrics.widthPixels;
    }

    public int getScreen_height() {
        return screen_height;
    }

    public int getScreen_width() {
        return screen_width;
    }
}
Satendra
  • 6,755
  • 4
  • 26
  • 46
4

I use the following code to get the screen dimensions

getWindow().getDecorView().getWidth()
getWindow().getDecorView().getHeight()
Harsha
  • 1,568
  • 2
  • 19
  • 22
  • This is not technically the screen dimensions but this is helpful since these dimensions do not contain stuff like status- and bottom bar – hordurh Apr 13 '21 at 07:49
4

Seems like all these answers fail for my Galaxy M51 with Android 11. After doing some research around I found this code :

WindowMetrics windowmetrics = MainActivity.getWindowManager().getCurrentWindowMetrics();
Rect rect = windowmetrics.getBounds();
int width = rect.right;
int height =rect.bottom;

shows my true device resolution of 1080x2400, the rest only return 810x1800.

RelativeGames
  • 1,593
  • 2
  • 18
  • 27
3

Methods shown here are deprecated/outdated but this is still working.Require API 13

check it out

Display disp= getWindowManager().getDefaultDisplay();
Point dimensions = new Point();
disp.getSize(size);
int width = size.x;
int height = size.y;
Hemant Shori
  • 2,463
  • 1
  • 22
  • 20
3

As an android official document said for the default display use Context#getDisplay() because this method was deprecated in API level 30.

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

This bowl of code help to determine width and height.

public static int getWidth(Context context) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    Display display = context.getDisplay();
    if (display != null) {
        display.getRealMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }
    return -1;
}

For the Height:

public static int getHeight(Context context) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    Display display = context.getDisplay();
    if (display != null) {
        display.getRealMetrics(displayMetrics);
        return displayMetrics.heightPixels;
    }
    return -1;
}
Kishan Donga
  • 2,851
  • 2
  • 23
  • 35
2

Try this code for Kotlin

 val display = windowManager.defaultDisplay
 val size = Point()
 display.getSize(size)
 var DEVICE_WIDTH = size.x
 var DEVICE_HEIGHT = size.y
Najib.Nj
  • 3,706
  • 1
  • 25
  • 39
1

Just use the function below that returns width and height of the screen size as an array of integers

private int[] getScreenSIze(){
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int h = displaymetrics.heightPixels;
        int w = displaymetrics.widthPixels;

        int[] size={w,h};
        return size;

    }

On your onCreate function or button click add the following code to output the screen sizes as shown below

 int[] screenSize= getScreenSIze();
        int width=screenSize[0];
        int height=screenSize[1];
        screenSizes.setText("Phone Screen sizes \n\n  width = "+width+" \n Height = "+height);
Tim
  • 41,901
  • 18
  • 127
  • 145
Daniel Nyamasyo
  • 2,152
  • 1
  • 24
  • 23
1

I updated answer for Kotlin language!

For Kotlin: You should call Window Manager and get metrics. After that easy way.

val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)

var width = displayMetrics.widthPixels
var height = displayMetrics.heightPixels

How can we use it effectively in independent activity way with Kotlin language?

Here, I created a method in general Kotlin class. You can use it in all activities.

private val T_GET_SCREEN_WIDTH:String = "screen_width"
private val T_GET_SCREEN_HEIGHT:String = "screen_height"

private fun getDeviceSizes(activity:Activity, whichSize:String):Int{

    val displayMetrics = DisplayMetrics()
    activity.windowManager.defaultDisplay.getMetrics(displayMetrics)

    return when (whichSize){
        T_GET_SCREEN_WIDTH -> displayMetrics.widthPixels
        T_GET_SCREEN_HEIGHT -> displayMetrics.heightPixels
        else -> 0 // Error
    }
}
ChrisF
  • 134,786
  • 31
  • 255
  • 325
canerkaseler
  • 6,204
  • 45
  • 38
  • 1
    Maybe even better solution would be to create an extension function for Activity class. – Micer May 12 '20 at 13:55
1
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)

var width = displayMetrics.widthPixels
var height = displayMetrics.heightPixels
Deniz Babat
  • 205
  • 2
  • 6
0

I found weigan's answer best one in this page, here is how you can use that in Xamarin.Android:

public int GetScreenWidth()
{
    return Resources.System.DisplayMetrics.WidthPixels;
}

public int GetScreenHeight()
{
    return Resources.System.DisplayMetrics.HeightPixels;
}
Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
0

Screen resolution is total no of pixel in screen. Following program will extract the screen resolution of the device. It will print screen width and height. Those values are in pixel.

public static Point getScreenResolution(Context context) {
// get window managers
WindowManager manager =  (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);

 // get width and height
 int width = point.x;
 int height = point.y;

 return point;

}

Fakhriddin Abdullaev
  • 4,169
  • 2
  • 35
  • 37
0
    int getScreenSize() {
        int screenSize = getResources().getConfiguration().screenLayout &
                Configuration.SCREENLAYOUT_SIZE_MASK;
//        String toastMsg = "Screen size is neither large, normal or small";
        Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        int orientation = display.getRotation();

        int i = 0;
        switch (screenSize) {

            case Configuration.SCREENLAYOUT_SIZE_NORMAL:
                i = 1;
//                toastMsg = "Normal screen";
                break;
            case Configuration.SCREENLAYOUT_SIZE_SMALL:
                i = 1;
//                toastMsg = "Normal screen";
                break;
            case Configuration.SCREENLAYOUT_SIZE_LARGE:
//                toastMsg = "Large screen";
                if (orientation == Surface.ROTATION_90
                        || orientation == Surface.ROTATION_270) {
                    // TODO: add logic for landscape mode here
                    i = 2;
                } else {
                    i = 1;
                }


                break;
            case Configuration.SCREENLAYOUT_SIZE_XLARGE:
                if (orientation == Surface.ROTATION_90
                        || orientation == Surface.ROTATION_270) {
                    // TODO: add logic for landscape mode here
                    i = 4;
                } else {
                    i = 3;
                }

                break;


        }
//        customeToast(toastMsg);
        return i;
    }
pruthwiraj.kadam
  • 1,033
  • 10
  • 11
0
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;

this may be not work in some case. for the getMetrics comments:

Gets display metrics that describe the size and density of this display. The size returned by this method does not necessarily represent the actual raw size (native resolution) of the display.

  1. The returned size may be adjusted to exclude certain system decor elements that are always visible.

  2. It may be scaled to provide compatibility with older applications that were originally designed for smaller displays.

  3. It can be different depending on the WindowManager to which the display belongs.

  • If requested from non-Activity context (e.g. Application context via (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)) metrics will report the size of the entire display based on current rotation and with subtracted system decoration areas.

  • If requested from activity (either using getWindowManager() or (WindowManager) getSystemService(Context.WINDOW_SERVICE)) resulting metrics will correspond to current app window metrics. In this case the size can be smaller than physical size in multi-window mode.

So, to get the real size:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;

or:

Point point = new Point();
getWindowManager().getDefaultDisplay().getRealSize(point);
int height = point.y;
int width = point.x;
zyc zyc
  • 3,805
  • 1
  • 14
  • 14
0
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
  public static double getHeight() {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    display.getRealMetrics(displayMetrics);

    //int height = displayMetrics.heightPixels;
    //int width = displayMetrics.widthPixels;
    return displayMetrics.heightPixels;
  }

Using that method you can get screen height. if you want to get width change displayMetrics.heightPixels to displayMetrics.widthPixels.

And it also include required api Build version.

dilshan
  • 2,045
  • 20
  • 18
-3
       @Override
        protected void onPostExecute(Drawable result) {
            Log.d("width",""+result.getIntrinsicWidth());
            urlDrawable.setBounds(0, 0, 0+result.getIntrinsicWidth(), 600);

            // change the reference of the current drawable to the result
            // from the HTTP call
            urlDrawable.drawable = result;

            // redraw the image by invalidating the container
            URLImageParser.this.container.invalidate();

            // For ICS
            URLImageParser.this.container.setHeight((400+URLImageParser.this.container.getHeight()
                    + result.getIntrinsicHeight()));

            // Pre ICS`enter code here`
            URLImageParser.this.container.setEllipsize(null);
        }
Aruttan Aru
  • 45
  • 1
  • 5