Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save astachelek/5542753 to your computer and use it in GitHub Desktop.
Save astachelek/5542753 to your computer and use it in GitHub Desktop.
In case you ever wanted to see a list of the various approaches to get the size of the screen in Android, here are a bunch. Many of these return slightly different values.
// This causes some IPC to the WindowManager, so use with caution as its slow
Rect displayArea = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayArea);
Log.d(TAG, "Visible Display Frame Method: " + displayArea.width() + "x" + displayArea.height());
// This is not immediately available as the full view layout needs to happen
View root = window.getDecorView().findViewById(android.R.id.content);
Log.d(TAG, "Root Content View Method: " + root.getMeasuredWidth() + "x" + root.getMeasuredHeight());
// This seems to be the most standard way
DisplayMetrics displaymetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
Log.d(TAG, "DisplayMetrics Method: " + displaymetrics.widthPixels + "x" + displaymetrics.heightPixels);
// This is deprecated
Display display = activity.getWindowManager().getDefaultDisplay();
Log.d(TAG, "Deprecated Display getters: " + display.getWidth() + "x" + display.getHeight());
// Another way
Rect outSize = new Rect() ;
display.getRectSize(outSize);
Log.d(TAG, "Display.getRectSize Method: " + outSize.width() + "x" + outSize.height());
// This attempts to get the full true screen resolution, but doesn't work across all platform versions
if (Build.VERSION.SDK_INT >= 16) {
display.getRealMetrics(metrics);
Log.d(TAG, "Display.getRealMetrics Method: " + metrics.widthPixels + "x" + metrics.heightPixels);
} else {
// Why would we ever need to use Reflection to do this?
try {
Method mGetRawH = Display.class.getMethod("getRawHeight");
Method mGetRawW = Display.class.getMethod("getRawWidth");
int realWidth = (Integer) mGetRawW.invoke(display);
int realHeight = (Integer) mGetRawH.invoke(display);
Log.d(TAG, "Reflection Method on Display: " + realWidth + "x" + realHeight);
} catch (Exception e) {
Log.e(TAG, "error", e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment