Android get Screen Size deprecated?

android, deprecated, size

Solution

I don't know whether these deprecated methods will work on Android 3 and 4. The best way to tell is to test on an emulator.

But, the safest method here for max compatibility will be to try one method using reflection, and fall back to the other. Essentially, you could make your own version of `getSize()` that can't fail. I can't test this atm, but it might look like this:

void overrideGetSize(Display display, Point outSize) {
    try {
      // test for new method to trigger exception
      Class pointClass = Class.forName("android.graphics.Point");
      Method newGetSize = Display.class.getMethod("getSize", new Class[]{ pointClass });

      // no exception, so new method is available, just use it
      newGetSize.invoke(display, outSize);
    } catch(NoSuchMethodException ex) {
      // new method is not available, use the old ones
      outSize.x = display.getWidth();
      outSize.y = display.getHeight();
    }
}

Then of course just call it with something like

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
overrideGetSize(display, size);

Problem

Hey I need to get the width of the screen in my application. The application will run on 2.1 and upwards. I have set it up like the one below. The method is deprecated and i should proabably use getSize or a other way. But the question is: Will this work on android versions like 3.0+ and 4.0+, or will it make the app crash. I have used a deprecated method in a thread before and it made the app crash on ice cream devices. Will the method below work ? ``` Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); ``` EDIT: I have tried the getSize but i dont get it to work: ``` Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int height = size.y; ```

Original source

Related problems