Android: get real screen size - android

Since API 17 it is possible to get the actual screen size of a phone with:
if (android.os.Build.VERSION.SDK_INT >= 17){
display.getRealSize(size);
int screen_width = size.x;
screen_height = size.y;
} else {...}
I want to get the real screen size for APIs 8-16. What is the best way to handle the else condition in this case?

The following is my solution for getting the actual screen height on all APIs. When the device has a physical navigation bar, dm.heightPixels returns the actual height. When the device has a software navigation bar, it returns the total height minus the bar. I have only tested on a few devices but this has worked so far.
int navBarHeight = 0;
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
navBarHeight = resources.getDimensionPixelSize(resourceId);
}
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
boolean hasPhysicalHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME);
if (android.os.Build.VERSION.SDK_INT >= 17){
display.getRealSize(size);
int screen_width = size.x;
screen_height = size.y;
} else if (hasPhysicalHomeKey){
screen_height = dm.heightPixels;
} else {
screen_height = dm.heightPixels + navBarHeight;
}

Try this code:
display.getRealSize();
More about visited this link:
http://developer.android.com/reference/android/view/Display.html
or
You look at url:
https://stackoverflow.com/a/1016941/3821823
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

else{
display.getWidth()
display.getHeight()
}
edit: alternative solution
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
metrics.widthPixels
metrics.heightPixels
from the docs:
The absolute width of the display in pixels.
if even after those method the device insist in not giving it's real size, I don't believe there will be much you can do without editing the build.prop file on the device.

Related

How to get phone screens height and width

I use this code to find the Height and width of the screen
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
But I get 1080 x 1920 for samsung galaxy S4 and 800 x 1280 for Nexus 7. But I actually need the the orginal heigth and width. How to get it.
I Hope this may help
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenHeight = metrics.heightPixels;
int screenWidth = metrics.widthPixels;
Log.i("MY", "Actual Screen Height = " + screenHeight + " Width = " + screenWidth);
If you mean the size without subtracting room for the status bars and other decorations- use Display.getRealSize().
Try this way:
final DisplayMetrics metrics = new DisplayMetrics();
Display display = getWindowManager().getDefaultDisplay();
Method mGetRawH = null,mGetRawW = null;
int realWidth=0,realHeight=0;
// For JellyBeans and onward
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1){
display.getRealMetrics(metrics);
realWidth = metrics.widthPixels;
realHeight = metrics.heightPixels;
} else{
// Below Jellybeans you can use reflection method
mGetRawH = Display.class.getMethod("getRawHeight");
mGetRawW = Display.class.getMethod("getRawWidth");
realWidth = (Integer) mGetRawW.invoke(display);
realHeight = (Integer) mGetRawH.invoke(display);
}
System.out.print(realWidth);
System.out.print(realHeight);
Normalize the pixel values using densityDpi value. This will give dimensions in terms of DP (density independent pixels).
int width = (displayMetrics.widthPixels * 160)/displayMetrics.densityDpi;
int height = (displayMetrics.heightPixels * 160)/displayMetrics.densityDpi;

how can i get the "real" resolution of my device?

Yes, I know I can use DisplayMetrics but the problem is that on some devices the widthPixels member is a wrong value (at least i have such one phone). The resolution in setting page is 720*1280, but widthPixels is 600 and heightPixels in DisplayMetrics is 1067.
Additionally, I have tried getRealSize and the returned value is correct. But eventually I found that the "real" width of my phone is 640 (and I guess the height is also a different number).
Awesome! what's really going on here?
Edit:
here're some data
widthPixels in DisplayMetrics is 600. density is 1.6, heightPixels is 1067.
And i have tried all your methods, but all not working. I won't need to post my question here if I could find the correct answer so easily. The device is HN3-U01, made in china
you can use this code..
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Try with this
private DisplayMetrics metrics;
private int widthPixels;
private float scaleFactor;
private float widthDp;
metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int density= getResources().getDisplayMetrics().densityDpi;
widthPixels = metrics.widthPixels;
scaleFactor = metrics.density;
widthDp = widthPixels / scaleFactor;
// Get device resolution
int width = 0;
int height = 0;
Point size = new Point();
WindowManager w = getWindowManager();
if (Build.VERSION.SDK_INT >= 13)
{
w.getDefaultDisplay().getSize(size);
width = size.x;
height = size.y;
}
else
{
Display display = getWindowManager().getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
}
because getWidth() and getHeight() method deprecated after API level 13

how to get total screen size on an android device programmatically

if i use the code shown here to get the total screen size it is always short on height to the total screen size as shown in the documented specs for the device. for example I tried to get the screen size by using the code to get the size for a tablet listed as 1280 X 800 and the result from the code is: 1216 X 800. so where is the missing 64 pixels going to?
i can guess that it could be the bar at the bottom of the screen that holds the back and home buttons. but that does not sound right as the content views is supposed to be the root of all views. what is going on here?
the only possible explanation could be this part of the UI
code used to get screen size
// gets the content view windows width and height size
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int widthContentView = displaymetrics.widthPixels;
int heightContentView = displaymetrics.heightPixels;
Toast.makeText(MainActivity.this, "width of content view: " + widthContentView Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "height of content view: " + heightContentView, Toast.LENGTH_SHORT).show();
If you're calling this outside of an Activity, you'll need to pass the context in (or get it through some other call). Then use that to get your display metrics:
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
I'm not sure what api you use but if you use api starting from 17 you can use this:
display.getRealSize();
try this code...
Display display = context.getWindowManager()
.getDefaultDisplay();
int width = display.getWidth();
int height=display.getHeight();
it will give screen's width and height,And according to width and height write if- conditions for each device's screen resolution.
You are right, It is showing you the resolution of your app screen and hence you getting the difference.Instead of getMetrics(), use getRealMetrics().
You can use the following code to get the actual screen size of device.
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getRealMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
return width + "*" + height;
int density;
private DisplayMetrics metrics;
private int widthPixels;
private float scaleFactor;
private float widthDp;
metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
density= getResources().getDisplayMetrics().densityDpi;
widthPixels = metrics.widthPixels;
scaleFactor = metrics.density;
widthDp = widthPixels / scaleFactor;
System.out.println("widthDp== "+widthDp );
if(density==DisplayMetrics.DENSITY_HIGH)
System.out.println("Density is high");
if(density==DisplayMetrics.DENSITY_XXHIGH)
System.out.println("Density is xxhigh");
if(density==DisplayMetrics.DENSITY_XXXHIGH)
System.out.println("Density is xxxhigh");
if(density==DisplayMetrics.DENSITY_TV)
System.out.println("Density is Tv");
int Measuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
WindowManager w = getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
} else {
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();;
}
After searching for hours through stackOverFlow, couldn't find a single answer that was up to date so thought I would share mine. Hope this helps. :)
Method 1 (Deprecated)
fun Resolution() : String {
var width : Int? = 0
var height : Int? = 0
try {
val displayMetrics = DisplayMetrics()
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager.defaultDisplay.getRealMetrics(displayMetrics)
width = displayMetrics.widthPixels
height = displayMetrics.heightPixels
}catch (e : Exception){
e.printStackTrace()
Log.e("DisplayClass", e.message, e)
}
return "$width x $height pixels"
}
Difference between getRealMetrics(displayMetrics) and getMetrics(displayMetrics) is that getMetrics() will return height/width without adding the size of status bars and navigation bars
windowManager.defaultDisplay.getRealMetrics(displayMetrics) // e.g: 1080 x 2340
windowManager.defaultDisplay.getMetrics(displayMetrics) // e.g: 1080 x 2260
Method 2 (Deprecated) (Minimum API : 30 (R))
This method returns the same result as getMetrics()
#RequiresApi(Build.VERSION_CODES.R)
fun Resolution() : String {
val width = context.display?.width
val height = context.display?.height
return "$width x $height"
}
Method 3 (Working as of 24th August 2022)
fun Resolution() : String {
var width: Int? = 0
var height : Int? = 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val metrics = windowManager.currentWindowMetrics
width = metrics.bounds.width()
height = metrics.bounds.height()
}else{
val displayMetrics = DisplayMetrics()
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager.defaultDisplay.getRealMetrics(displayMetrics)
width = displayMetrics.widthPixels
height = displayMetrics.heightPixels
}
return "$width x $height"
}
Get all Display set your width and height as you required.
Display display;
display=getWindowManager().getDefaultDisplay();
text1.setWidth(display.getWidth()-380);
text1.setHeight(display.getHeight()-720);

Getting screen size return 0

I am trying to get the screen size on my emulator (API 7) with this code:
float scaledDensity = this.getResources().getDisplayMetrics().scaledDensity;
Now I try to use scaledDensity
with this code:
int width = (width / ((int) scaledDensity)) / 7;
and I get this exception
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tomer.workoutlog2/com.example.workoutlog.SimpleCalendarViewActivity}: java.lang.ArithmeticException: divide by zero
Full code:
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE))
.getDefaultDisplay();
int width = 0;
if (android.os.Build.VERSION.SDK_INT >= 13) {
Point size = new Point();
display.getSize(size);
width = size.x;
} else
width = display.getWidth();
float scaledDensity = this.getResources().getDisplayMetrics().scaledDensity;
width = (width / ((int) scaledDensity)) / 7;
On my real device I don't get this error.
Maybe, is the problem with the emulator?
for API 7 you can use the following code, it is deprecated from API 13
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
scaledDensity() returns a float. Sure you are not accidentally doing a integer division with an float less than 1.0f?
Try this...
DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
Try this code:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
float scaleFactor = displaymetrics.density;

How to get real screen height and width?

DisplayMetrics metrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenWidth = metrics.widthPixels;
screenHeight = metrics.heightPixels;
I use these codes to get the height and width of screen
the screen height on my Nexus7 should be 1280
but it return 1205...
and my minSdkVersion is level 8
so i can't use these method:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screen_width = size.x;
int screen_height = size.y;
now, how should i get the correct screen size ?
Edit:
if (Build.VERSION.SDK_INT >= 11) {
Point size = new Point();
try {
this.getWindowManager().getDefaultDisplay().getRealSize(size);
screenWidth = size.x;
screenHeight = size.y;
} catch (NoSuchMethodError e) {
Log.i("error", "it can't work");
}
} else {
DisplayMetrics metrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenWidth = metrics.widthPixels;
screenHeight = metrics.heightPixels;
}
use it works!
I've written a method that will get as close as possible for API 10 through 17+. It should give the real width and height for API 14+, and it does as well as it can for everything else.
Display display = context.getWindowManager().getDefaultDisplay();
int realWidth;
int realHeight;
if (Build.VERSION.SDK_INT >= 17){
//new pleasant way to get real metrics
DisplayMetrics realMetrics = new DisplayMetrics();
display.getRealMetrics(realMetrics);
realWidth = realMetrics.widthPixels;
realHeight = realMetrics.heightPixels;
} else if (Build.VERSION.SDK_INT >= 14) {
//reflection for this weird in-between time
try {
Method mGetRawH = Display.class.getMethod("getRawHeight");
Method mGetRawW = Display.class.getMethod("getRawWidth");
realWidth = (Integer) mGetRawW.invoke(display);
realHeight = (Integer) mGetRawH.invoke(display);
} catch (Exception e) {
//this may not be 100% accurate, but it's all we've got
realWidth = display.getWidth();
realHeight = display.getHeight();
Log.e("Display Info", "Couldn't use reflection to get the real display metrics.");
}
} else {
//This should be close, as lower API devices should not have window navigation bars
realWidth = display.getWidth();
realHeight = display.getHeight();
}
I think this will work. The trick is you must use:
display.getRealSize(size);
not
display.getSize(size);
To deal with your API 8 coding issue do something like this:
try {
display.getRealSize(size);
height = size.y;
} catch (NoSuchMethodError e) {
height = display.getHeight();
}
Only more recent API devices will have onscreen navigation buttons and thus need the new method, older devices will throw an exception but will not have onscreen navigation thus the older method is fine.
In case it needs to be said: Just because you have a minimumAPI level of 8 for your project doesn't mean you have to compile it at that level. I also use level 8 for minimum but my project mostly are compiled at level 13 (3.2) giving them access to a lot of new methods.
You can find real device dimensions with either using Display or DisplayMetrics
Using Display:
private void findRealSize(Activity activity)
{
Point size = new Point();
Display display = activity.getWindowManager().getDefaultDisplay();
if (Build.VERSION.SDK_INT >= 17)
display.getRealSize(size);
else
display.getSize(size);
int realWidth = size.x;
int realHeight = size.y;
Log.i("LOG_TAG", "realWidth: " + realWidth + " realHeight: " + realHeight);
}
Using DisplayMetrics:
private void findRealSize(Activity activity)
{
DisplayMetrics displayMetrics = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= 17)
{
activity.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
}
else
{
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
}
int realWidth = displayMetrics.widthPixels;
int realHeight = displayMetrics.heightPixels;
Log.i("LOG_TAG", "realWidth: " + realWidth + " realHeight: " + realHeight);
}

Categories

Resources