62

So i have a small problem, i'm writing a function which need to send screen width to server. I got it all to work, and i use:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();

to get width. However .getWidht() function is deprecated and it says u need to use:

Point size = new Point();
display.getSize(size);

But that function is only avaible for api level 13 or more, and my minimum sdk is 8. So what can i do? Is it safe if i stay with getWidth? Why adding new function and not make them backward compatible?

slezadav
  • 6,104
  • 7
  • 40
  • 61
gabrjan
  • 3,080
  • 9
  • 40
  • 69

4 Answers4

132

May be this approach will be helpful:

DisplayMetrics displaymetrics = new DisplayMetrics();
mContext.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int screenWidth = displaymetrics.widthPixels;
int screenHeight = displaymetrics.heightPixels;
iBog
  • 2,245
  • 1
  • 20
  • 15
11

You can check for API level at runtime, and choose which to use, e.g.:

final int version = android.os.Build.VERSION.SDK_INT;
final int width;
if (version >= 13)
{
    Point size = new Point();
    display.getSize(size);
    width = size.x;
}
else
{
    Display display = getWindowManager().getDefaultDisplay(); 
    width = display.getWidth();
}
nmw
  • 6,664
  • 3
  • 31
  • 32
5

Here is the latest Code without Deprecation.

Kotlin

 val metrics: DisplayMetrics = this.getResources().getDisplayMetrics()
 val width = metrics.widthPixels

Java

  DisplayMetrics metrics = context.getResources().getDisplayMetrics();
  int width = metrics.widthPixels;
  int height = metrics.heightPixels;
Faizan Haidar Khan
  • 1,099
  • 1
  • 15
  • 20
4

If you want to be correct, use this approach:

int sdk = android.os.Build.VERSION.SDK_INT;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();
} else {
    Point size = new Point();
    display.getSize(size);
}
Jose Gómez
  • 3,110
  • 2
  • 32
  • 54
slezadav
  • 6,104
  • 7
  • 40
  • 61
  • 2
    You're comparing an int against a String (VERSION.RELEASE) there. – nmw Oct 09 '12 at 20:50
  • 4
    If you wanted to be correct you wouldn't compare an int to a String and you wouldn't store the int in a non final local variable, hell you don't even need that variable, why store it in the 1st place. ;) You proably want to do `if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {` – Martin Marconcini May 30 '14 at 19:26
  • display.getSize is also deprecated – Sérgio S. Filho Sep 12 '20 at 06:18