Related
I'd like to get the size of the screen of the phones but it keeps giving me wrong values, I already used
WindowManager windowmanager = (WindowManager)
getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
Display display = windowmanager.getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);
float deviceWidth = displayMetrics.widthPixels;
float deviceHeight = displayMetrics.ydpi;
I tried this code too :
Resources resources = getResources();
Configuration config = resources.getConfiguration();
DisplayMetrics dm = resources.getDisplayMetrics();
// Note, screenHeightDp isn't reliable
// (it seems to be too small by the height of the status bar),
// but we assume screenWidthDp is reliable.
// Note also, dm.widthPixels,dm.heightPixels aren't reliably pixels
// (they get confused when in screen compatibility mode, it seems),
// but we assume their ratio is correct.
double screenWidthInPixels = (double)config.screenWidthDp *dm.density;
double screenHeightInPixels = screenWidthInPixels * dm.heightPixels / dm.widthPixels;
deviceWidth = (int)(screenWidthInPixels + .5);
deviceHeight = (int)(screenHeightInPixels + .5);
And also that :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Point realSize = new Point();
display.getRealSize(realSize);
deviceWidth= realSize.x;
deviceHeight = realSize.y;
}
But on my Samsung S7 on sdk 7.0 I got 1920x1080 that is wrong because on a S7 on sdk 6.0.1 I got 2560x1440 that is the real value.
I tried a lot of solution but found nothing good.
Thanks
Your code is correct. Just in case if you wondering why you get that values, it is because your phone will automatically set the default resolution size to 1920x1080 after updated to 7.0 (Nougat) to conserve the battery life. One of the new features in Nougat is display scaling option, where you can set your phone (in this case, S7) to 3 available modes (WQHD (2560x1440), FHD (1920x1080), and HD (1280x720)). Try go to Settings -> Display and change the settings to your needs. You can read more here: Galaxy S7 on Nougat defaults to 1080p
use this
getWindowManager().getDefaultDisplay().getHeight();
getWindowManager().getDefaultDisplay().getWidth();
This will work for sure.
try {
display.getRealSize(size);
height = size.y;
width=size.x;
} catch (NoSuchMethodError e) {
height = display.getHeight();
width=display.getWidth();
}
Try this link
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
The method below return a Point that contain display size (x as Width and y as Height):
public static Point checkDisplaySize(Context context) {
Point tempDisplaySize = new Point();
try {
WindowManager manager = (WindowManager) context().getSystemService(Context.WINDOW_SERVICE);
if (manager != null) {
Display display = manager.getDefaultDisplay();
if (display != null) {
display.getSize(tempDisplaySize);
Log.d("tmessages", "display size = " + displaySize.x + " " + displaySize.y);
}
}
} catch (Exception e) {
Log.e("tmessages", e.getMessage(), e);
}
return tempDisplaySize;
}
P.S: This is the Code Telegram uses to get display size.
In android it is possible to lock the screen orientation by adding this to the manifest :
android:screenOrientation="landscape"
But is it possible to lock within the size?
I want my app to be locked in portrait for phone format, and I want the user beeing able to use both portrait and landscape on a tablet format.
I've tried with screen size by using :
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
but it doesn't seem to work when I want to lock screen from code. Any idea of a good way to do this?
first check this answer
now you can change orientation like this
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (!tabletSize) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
You can get the diagonal Value of the device by following
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
float yInches= metrics.heightPixels/metrics.ydpi;
float xInches= metrics.widthPixels/metrics.xdpi;
double diagonalInches = Math.sqrt(xInches*xInches + yInches*yInches);
After that you can check according to your need if you want the size of 5,5.5,6,6.5 or higher and change orientation according to need
if (diagonalInches>=6.5){
// 6.5inch device or bigger
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}else{
// smaller device
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
You can create a custom method to check the current screen density of phone,
public static boolean isTabLayout(Activity activity) {
DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;
float scaleFactor = metrics.density;
float widthDp = widthPixels / scaleFactor;
float heightDp = heightPixels / scaleFactor;
float smallestWidth = Math.min(widthDp, heightDp);
if (smallestWidth > 720) {
//Device is a 10" tablet
return true;
} else if (smallestWidth > 600) {
//Device is a 7" tablet
return true;
}
return false;
}
To lock the screen orientation in portrait,
if (!isTabLayout(this)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
or in landscape,
if (!isTabLayout(this)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
Use This:
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
public void setOrientation(Context context){
if(!isTablet(contex){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
I don't know exactly its working or not try this
TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
if(manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE){
return "Tablet";
}else{
return "Mobile";
}
or look this once Determine if the device is a smartphone or tablet?
Android defines screen sizes as Normal Large XLarge etc.
It automatically picks between static resources in appropriate folders. I need this data about the current device in my java code. The DisplayMetrics only gives information about the current device density. Nothing is available regarding screen size.
I did find the ScreenSize enum in grep code here
However this does not seem available to me for 4.0 SDK. Is there a way to get this information?
Copy and paste this code into your Activity and when it is executed it will Toast the device's screen size category.
int screenSize = getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK;
String toastMsg;
switch(screenSize) {
case Configuration.SCREENLAYOUT_SIZE_LARGE:
toastMsg = "Large screen";
break;
case Configuration.SCREENLAYOUT_SIZE_NORMAL:
toastMsg = "Normal screen";
break;
case Configuration.SCREENLAYOUT_SIZE_SMALL:
toastMsg = "Small screen";
break;
default:
toastMsg = "Screen size is neither large, normal or small";
}
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
private static String getScreenResolution(Context context)
{
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
return "{" + width + "," + height + "}";
}
I think it is a pretty straight forward simple piece of code!
public Map<String, Integer> deriveMetrics(Activity activity) {
try {
DisplayMetrics metrics = new DisplayMetrics();
if (activity != null) {
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
}
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("screenWidth", Integer.valueOf(metrics.widthPixels));
map.put("screenHeight", Integer.valueOf(metrics.heightPixels));
map.put("screenDensity", Integer.valueOf(metrics.densityDpi));
return map;
} catch (Exception err) {
; // just use zero values
return null;
}
}
This method now can be used anywhere independently. Wherever you want to get information about device screen do it as follows:
Map<String, Integer> map = deriveMetrics2(this);
map.get("screenWidth");
map.get("screenHeight");
map.get("screenDensity");
Hope this might be helpful to someone out there and may find it easier to use.
If I need to re-correct or improve please don't hesitate to let me know! :-)
Cheers!!!
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
Ways to get DisplayMetrics:
1.
val dm = activity.resources.displayMetrics
val dm = DisplayMetrics()
activity.windowManager.defaultDisplay.getMetrics(dm)
val dm = DisplayMetrics()
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
wm..defaultDisplay.getMetrics(dm)
then get
The screen density expressed as dots-per-inch. May be either DENSITY_LOW, DENSITY_MEDIUM, or DENSITY_HIGH
dm.densityDpi
The absolute height of the available display size in pixels.
dm.heightPixels
The absolute width of the available display size in pixels.
dm.widthPixels
The exact physical pixels per inch of the screen in the X dimension.
dm.xdpi
The exact physical pixels per inch of the screen in the Y dimension.
dm.ydpi
DisplayMetrics
You can get display size in pixels using this code.
Display display = getWindowManager().getDefaultDisplay();
SizeUtils.SCREEN_WIDTH = display.getWidth();
SizeUtils.SCREEN_HEIGHT = display.getHeight();
With decorations (including button bar):
private static String getScreenResolution(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRealMetrics(metrics);
return "{" + metrics.widthPixels + "," + metrics.heightPixels + "}";
}
Without decorations:
private static String getScreenResolution(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
return "{" + metrics.widthPixels + "," + metrics.heightPixels + "}";
}
The difference is the method getMetrics() vs getRealMetrics() of the Display class.
The code will give you the result in the following format: width x height
String displayResolution = getResources().getDisplayMetrics().widthPixels + "x" + getResources().getDisplayMetrics().heightPixels;
simon-
Different screen sizes have different pixel densities. A 4 inch display on your phone could have more or less pixels then say a 26 inch TV. If Im understanding correctly he wants to detect which of the size groups the current screen is, small, normal, large, and extra large. The only thing I can think of is to detect the pixel density and use that to determine the actual size of the screen.
I need this for a couple of my apps and the following code was my solution to the problem. Just showing the code inside onCreate. This is a stand alone app to run on any device to return the screen info.
setContentView(R.layout.activity_main);
txSize = (TextView) findViewById(R.id.tvSize);
density = (TextView) findViewById(R.id.density);
densityDpi = (TextView) findViewById(R.id.densityDpi);
widthPixels = (TextView) findViewById(R.id.widthPixels);
xdpi = (TextView) findViewById(R.id.xdpi);
ydpi = (TextView) findViewById(R.id.ydpi);
Configuration config = getResources().getConfiguration();
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
Toast.makeText(this, "Large screen", Toast.LENGTH_LONG).show();
txSize.setText("Large screen");
} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
Toast.makeText(this, "Normal sized screen", Toast.LENGTH_LONG)
.show();
txSize.setText("Normal sized screen");
} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
Toast.makeText(this, "Small sized screen", Toast.LENGTH_LONG)
.show();
txSize.setText("Small sized screen");
} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
Toast.makeText(this, "xLarge sized screen", Toast.LENGTH_LONG)
.show();
txSize.setText("Small sized screen");
} else {
Toast.makeText(this,
"Screen size is neither large, normal or small",
Toast.LENGTH_LONG).show();
txSize.setText("Screen size is neither large, normal or small");
}
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
Log.i(TAG, "density :" + metrics.density);
density.setText("density :" + metrics.density);
Log.i(TAG, "D density :" + metrics.densityDpi);
densityDpi.setText("densityDpi :" + metrics.densityDpi);
Log.i(TAG, "width pix :" + metrics.widthPixels);
widthPixels.setText("widthPixels :" + metrics.widthPixels);
Log.i(TAG, "xdpi :" + metrics.xdpi);
xdpi.setText("xdpi :" + metrics.xdpi);
Log.i(TAG, "ydpi :" + metrics.ydpi);
ydpi.setText("ydpi :" + metrics.ydpi);
And a simple XML file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="#+id/tvSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/density"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/densityDpi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/widthPixels"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/xdpi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/ydpi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
If you are in a non-activity i.e. Fragment, Adapter, Model class or any other java class that do not extends Activity simply getResources() will not work. You can use getActivity() in fragment or use context that you pass to the corresponding class.
mContext.getResources()
I would recommend making a class say Utils that will have method/Methods for the common work. The benefit for this is you can get desired result with single line of code anywhere in the app calling this method.
The algorithm below can be used to identify which category will be used for picking between the static resources and also caters for the newer XX and XXX high densities
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
mDensityDpi = displayMetrics.densityDpi;
mDensity = displayMetrics.density;
mDisplayWidth = displayMetrics.widthPixels;
mDisplayHeight = displayMetrics.heightPixels;
String densityStr = "Unknown";
int difference, leastDifference = 9999;
difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_LOW);
if (difference < leastDifference) {
leastDifference = difference;
densityStr = "LOW";
}
difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_MEDIUM);
if (difference < leastDifference) {
leastDifference = difference;
densityStr = "MEDIUM";
}
difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_HIGH);
if (difference < leastDifference) {
leastDifference = difference;
densityStr = "HIGH";
}
difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_XHIGH);
if (difference < leastDifference) {
leastDifference = difference;
densityStr = "XHIGH";
}
difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_XXHIGH);
if (difference < leastDifference) {
leastDifference = difference;
densityStr = "XXHIGH";
}
difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_XXXHIGH);
if (difference < leastDifference) {
densityStr = "XXXHIGH";
}
Log.i(TAG, String.format("Display [h,w]: [%s,%s] Density: %s Density DPI: %s [%s]", mDisplayHeight, mDisplayWidth, mDensity, mDensityDpi, densityStr));
Get screen resolution or screen size in Kotlin
fun getScreenResolution(context: Context): Pair<Int, Int> {
try {
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
val metrics = DisplayMetrics()
display.getMetrics(metrics)
val width = metrics.widthPixels
val height = metrics.heightPixels
//Log.d(AppData.TAG, "screenSize: $width, $height")
return Pair(width, height)
} catch (error: Exception) {
Log.d(AppData.TAG, "Error : autoCreateTable()", error)
}
return Pair(0, 0)
}
My case is that the logic is same for both Phone and Tablet. But there is slight difference in the layout. And I tried with the following code
public static boolean findoutDeviceType(Context context)
{
return (context.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK)>=
Configuration.SCREENLAYOUT_SIZE_LARGE;
}
Samsung Tab 10" has the resolution of 1280 * 800 and S3 has the resolution of 1270 * 720. And this code returns the Size as XLarge for both the Tab and Phone as its criteria for checking is > 960 * 720.
I have tested inserting the respective UI in the layout folder in Res as Layout, Layout-Large and Layout-xLarge . But this didn't effect in anyway. while checking it took the UI from the Layout folder.
Anyway even though I place the UI in the different layout folders, I have to check them in the class file to set the respective ContentView.
Is there any other way to find it?
This subject is discussed in the Android Training:
http://developer.android.com/training/multiscreen/screensizes.html#TaskUseSWQuali
Here is implementation,
Credit goes to ol_v_er for this simple and easy approach.
Some additional Information
You have now flag indicate whether your application is running on phone or tablet.
I have created two packages to handle UI and it's functionality,
com.phone
com.tablet
And you redirect control to your needed package
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (tabletSize) {
// do something
//Start activity for tablet
} else {
// do something else
//Start activity for phone
}
Refer
Note :I think for both 10 inch and 7 inch screen app take resources from res/values-sw600dp/ . But To be more specific I think for 10 inch tablet screen we can use res/values-sw720dp/
<resources>
<bool name="isTablet">true</bool>
</resources>
Try this
public boolean isTablet(Context context) {
boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
return (xlarge || large);
}
It will return true if you are using a tablet. It has been checked on Samsung Galaxy Tab 7" and Samsung Galaxy S3.
For example, you could set some res-values folder:
res/values-xlarge
res/values-large
res/values-sw600dp
etc. Then You could declare a boolean for each one:
<resources>
<bool name="isXLarge">true</bool>
</resources>
or
<resources>
<bool name="isLarge">true</bool>
</resources>
you can get the value by
boolean xlargeValue = getResources().getBoolean(R.bool.isXlarge);
boolean largevalue = getResources().getBoolean(R.bool.isLarge);
boolean tabletValue = getResources().getBoolean(R.bool.sw620dp):
Try this code your app is working device phone or tablet easy to fine call the method oncreate() inside
isTabletDevice(activity)
private static boolean isTabletDevice(Context activityContext) {
boolean device_large = ((activityContext.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE)
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) activityContext;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (device_large) {
//Tablet
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT){
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM){
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_TV){
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_HIGH){
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_280){
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_400) {
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_XXHIGH) {
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_560) {
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_XXXHIGH) {
return true;
}
}else{
//Mobile
}
return false;
}
Old question, but this might help someone.
If you want to find out if device is tablet (screen lager than 7"), or phone, you can use this util method:
Kotlin
fun isTablet(): Boolean {
return App.instance.resources.configuration.smallestScreenWidthDp >= 600
}
Java
public static Boolean isTablet(){
return App.instance.resources.configuration.smallestScreenWidthDp >= 600
}
App.instance is aplication instance.
public boolean isTablet() {
try {
// Compute screen size
Context context = this;
DisplayMetrics dm =
context.getResources().getDisplayMetrics();
float screenWidth = dm.widthPixels / dm.xdpi;
float screenHeight = dm.heightPixels / dm.ydpi;
double size = Math.sqrt(Math.pow(screenWidth, 2) +
Math.pow(screenHeight, 2));
// Tablet devices have a screen size greater than 6
inches
return size >= 6;
} catch(Throwable t) {
Log.e("Failed to compute screen size", t.toString());
return false;
}
}
Try this code. You can get the screen inches, On the basis of size you can get the tablet or android device
String inputSystem;
inputSystem = android.os.Build.ID;
Log.d("hai",inputSystem);
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
Log.d("hai",width+"");
Log.d("hai",height+"");
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(width/dm.xdpi,2);
double y = Math.pow(height/dm.ydpi,2);
double screenInches = Math.sqrt(x+y);
Log.d("hai","Screen inches : " + screenInches+"");
Use different resource files rather than trying to determine it programmatically. This will be enough for the majority of cases and is what the documentation recommends.
See my fuller answer here.
All other questions use resource qualifiers and methods, which do not represent the PHYSICAL size of the device, but the AVAILABLE screen size. For example, in the multi-window mode, the system will get resources from the "values" folder instead of "values-large", because the available screen size for the app became smaller. To determine, whether the physical device is a tablet or phone, use the following method (I use 640x480dp as the minimum size for a tablet, which is the definition of large devices, feel free to change these constants):
fun isTablet(context: Context): Boolean {
val outSize = Point()
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager.defaultDisplay.getRealSize(outSize)
outSize.x = pxToDp(windowManager, outSize.x)
outSize.y = pxToDp(windowManager, outSize.y)
val shorterSideDp: Int
val longerSideDp: Int
if (outSize.x > outSize.y) {
shorterSideDp = outSize.y
longerSideDp = outSize.x
} else {
shorterSideDp = outSize.x
longerSideDp = outSize.y
}
return shorterSideDp > 480 && longerSideDp > 640
}
Function for converting PX to DP:
#Dimension(unit = Dimension.DP)
fun pxToDp(windowManager: WindowManager, #Dimension(unit = Dimension.PX) px: Int): Int {
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getRealMetrics(displayMetrics)
return (px / displayMetrics.densityDpi.toFloat() * DisplayMetrics.DENSITY_DEFAULT).roundToInt()
}
This is working perfectly well in my app:
private boolean isPhoneDevice(){
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
}
Android defines screen sizes as Normal Large XLarge etc.
It automatically picks between static resources in appropriate folders. I need this data about the current device in my java code. The DisplayMetrics only gives information about the current device density. Nothing is available regarding screen size.
I did find the ScreenSize enum in grep code here
However this does not seem available to me for 4.0 SDK. Is there a way to get this information?
Copy and paste this code into your Activity and when it is executed it will Toast the device's screen size category.
int screenSize = getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK;
String toastMsg;
switch(screenSize) {
case Configuration.SCREENLAYOUT_SIZE_LARGE:
toastMsg = "Large screen";
break;
case Configuration.SCREENLAYOUT_SIZE_NORMAL:
toastMsg = "Normal screen";
break;
case Configuration.SCREENLAYOUT_SIZE_SMALL:
toastMsg = "Small screen";
break;
default:
toastMsg = "Screen size is neither large, normal or small";
}
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
private static String getScreenResolution(Context context)
{
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
return "{" + width + "," + height + "}";
}
I think it is a pretty straight forward simple piece of code!
public Map<String, Integer> deriveMetrics(Activity activity) {
try {
DisplayMetrics metrics = new DisplayMetrics();
if (activity != null) {
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
}
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("screenWidth", Integer.valueOf(metrics.widthPixels));
map.put("screenHeight", Integer.valueOf(metrics.heightPixels));
map.put("screenDensity", Integer.valueOf(metrics.densityDpi));
return map;
} catch (Exception err) {
; // just use zero values
return null;
}
}
This method now can be used anywhere independently. Wherever you want to get information about device screen do it as follows:
Map<String, Integer> map = deriveMetrics2(this);
map.get("screenWidth");
map.get("screenHeight");
map.get("screenDensity");
Hope this might be helpful to someone out there and may find it easier to use.
If I need to re-correct or improve please don't hesitate to let me know! :-)
Cheers!!!
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
Ways to get DisplayMetrics:
1.
val dm = activity.resources.displayMetrics
val dm = DisplayMetrics()
activity.windowManager.defaultDisplay.getMetrics(dm)
val dm = DisplayMetrics()
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
wm..defaultDisplay.getMetrics(dm)
then get
The screen density expressed as dots-per-inch. May be either DENSITY_LOW, DENSITY_MEDIUM, or DENSITY_HIGH
dm.densityDpi
The absolute height of the available display size in pixels.
dm.heightPixels
The absolute width of the available display size in pixels.
dm.widthPixels
The exact physical pixels per inch of the screen in the X dimension.
dm.xdpi
The exact physical pixels per inch of the screen in the Y dimension.
dm.ydpi
DisplayMetrics
You can get display size in pixels using this code.
Display display = getWindowManager().getDefaultDisplay();
SizeUtils.SCREEN_WIDTH = display.getWidth();
SizeUtils.SCREEN_HEIGHT = display.getHeight();
With decorations (including button bar):
private static String getScreenResolution(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRealMetrics(metrics);
return "{" + metrics.widthPixels + "," + metrics.heightPixels + "}";
}
Without decorations:
private static String getScreenResolution(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
return "{" + metrics.widthPixels + "," + metrics.heightPixels + "}";
}
The difference is the method getMetrics() vs getRealMetrics() of the Display class.
The code will give you the result in the following format: width x height
String displayResolution = getResources().getDisplayMetrics().widthPixels + "x" + getResources().getDisplayMetrics().heightPixels;
simon-
Different screen sizes have different pixel densities. A 4 inch display on your phone could have more or less pixels then say a 26 inch TV. If Im understanding correctly he wants to detect which of the size groups the current screen is, small, normal, large, and extra large. The only thing I can think of is to detect the pixel density and use that to determine the actual size of the screen.
I need this for a couple of my apps and the following code was my solution to the problem. Just showing the code inside onCreate. This is a stand alone app to run on any device to return the screen info.
setContentView(R.layout.activity_main);
txSize = (TextView) findViewById(R.id.tvSize);
density = (TextView) findViewById(R.id.density);
densityDpi = (TextView) findViewById(R.id.densityDpi);
widthPixels = (TextView) findViewById(R.id.widthPixels);
xdpi = (TextView) findViewById(R.id.xdpi);
ydpi = (TextView) findViewById(R.id.ydpi);
Configuration config = getResources().getConfiguration();
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
Toast.makeText(this, "Large screen", Toast.LENGTH_LONG).show();
txSize.setText("Large screen");
} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
Toast.makeText(this, "Normal sized screen", Toast.LENGTH_LONG)
.show();
txSize.setText("Normal sized screen");
} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
Toast.makeText(this, "Small sized screen", Toast.LENGTH_LONG)
.show();
txSize.setText("Small sized screen");
} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
Toast.makeText(this, "xLarge sized screen", Toast.LENGTH_LONG)
.show();
txSize.setText("Small sized screen");
} else {
Toast.makeText(this,
"Screen size is neither large, normal or small",
Toast.LENGTH_LONG).show();
txSize.setText("Screen size is neither large, normal or small");
}
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
Log.i(TAG, "density :" + metrics.density);
density.setText("density :" + metrics.density);
Log.i(TAG, "D density :" + metrics.densityDpi);
densityDpi.setText("densityDpi :" + metrics.densityDpi);
Log.i(TAG, "width pix :" + metrics.widthPixels);
widthPixels.setText("widthPixels :" + metrics.widthPixels);
Log.i(TAG, "xdpi :" + metrics.xdpi);
xdpi.setText("xdpi :" + metrics.xdpi);
Log.i(TAG, "ydpi :" + metrics.ydpi);
ydpi.setText("ydpi :" + metrics.ydpi);
And a simple XML file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="#+id/tvSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/density"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/densityDpi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/widthPixels"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/xdpi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/ydpi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
If you are in a non-activity i.e. Fragment, Adapter, Model class or any other java class that do not extends Activity simply getResources() will not work. You can use getActivity() in fragment or use context that you pass to the corresponding class.
mContext.getResources()
I would recommend making a class say Utils that will have method/Methods for the common work. The benefit for this is you can get desired result with single line of code anywhere in the app calling this method.
The algorithm below can be used to identify which category will be used for picking between the static resources and also caters for the newer XX and XXX high densities
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
mDensityDpi = displayMetrics.densityDpi;
mDensity = displayMetrics.density;
mDisplayWidth = displayMetrics.widthPixels;
mDisplayHeight = displayMetrics.heightPixels;
String densityStr = "Unknown";
int difference, leastDifference = 9999;
difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_LOW);
if (difference < leastDifference) {
leastDifference = difference;
densityStr = "LOW";
}
difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_MEDIUM);
if (difference < leastDifference) {
leastDifference = difference;
densityStr = "MEDIUM";
}
difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_HIGH);
if (difference < leastDifference) {
leastDifference = difference;
densityStr = "HIGH";
}
difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_XHIGH);
if (difference < leastDifference) {
leastDifference = difference;
densityStr = "XHIGH";
}
difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_XXHIGH);
if (difference < leastDifference) {
leastDifference = difference;
densityStr = "XXHIGH";
}
difference = Math.abs(mDensityDpi - DisplayMetrics.DENSITY_XXXHIGH);
if (difference < leastDifference) {
densityStr = "XXXHIGH";
}
Log.i(TAG, String.format("Display [h,w]: [%s,%s] Density: %s Density DPI: %s [%s]", mDisplayHeight, mDisplayWidth, mDensity, mDensityDpi, densityStr));
Get screen resolution or screen size in Kotlin
fun getScreenResolution(context: Context): Pair<Int, Int> {
try {
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
val metrics = DisplayMetrics()
display.getMetrics(metrics)
val width = metrics.widthPixels
val height = metrics.heightPixels
//Log.d(AppData.TAG, "screenSize: $width, $height")
return Pair(width, height)
} catch (error: Exception) {
Log.d(AppData.TAG, "Error : autoCreateTable()", error)
}
return Pair(0, 0)
}