Android getting screen size

Get screen size in Android

It seems in Android there are two ways to get screen width & height:

Both ways get screen width and height in pixels. So, I get a bit confused about the following two questions:

Q1. What are the differences between these two screen sizes theoritically?

Q2. Why google provide two ways to get screen size? I think there must be a reason behind it.

3 Answers 3

You should read about those two Classes

Window Manager gets screen width and height by getting the width and height of display that the window manager instance is managing including secondary display.

Getting width and height from Resources return the current display metrics and the objects should be treated as Read Only.

looking at the docs about DisplayMetrics :

A structure describing general information about a display, such as its size, density, and font scaling.

It seems that the DisplayMetrics class provides you with basic hardware display information. It does not care about any system UI components that may (or may not) be present.

While the Display class is more extended and takes the things mentioned above into account.

To answer your question:

will provide you with absolute values, i.e. you will always get 1080/1920 on a full HD display.

The description of the getSize() method is pretty much self-explanatory:

[. ] The size returned by this method does not necessarily represent the actual raw size (native resolution) of the display. The returned size may be adjusted to exclude certain system decoration elements that are always visible. [. ]

Источник

Is there a way to determine android physical screen height in cm or inches?

I need to know exactly how big the screen is on the device in real units of length so I can calculate the acceleration due to gravity in pixels per millisecond.

Is there a method somewhere in the Android API for this?

7 Answers 7

Use the following:

When mWidthPixels and mHeightPixels are taken from below code

15 test devices and it fails on some of them, e.g it is not working on some models like Motorola Milestone or ZTE phones.

for getting the current size use Math.round at the end.

use xdpi * widthPixels and ydpi * heightPixels might get you what you want i think.

Following code snippet will help you to get Screen Size in Inches

I used this to get the real size

I have tried most of the ways mentioned in the other answers, but those methods fail on particular devices. So here is bit of my contribution to solving this problem. The code is written in Kotlin

Get the DisplayMetrics object :

Calculate the Screen width in inches as follows :

Here, I have calculated the width of device in terms of dot points(dp) using widthPixels and then converted it to width in terms of inches. I have used 160 .i.e DisplayMetrics.DENSITY_MEDIUM as conversion factor to convert the widthPixels to widthInDotPoints.

Similarly, calculate the Screen Height in inches :

You need to use the screen density to calculate this.

According to the documentation:

The logical density of the display. This is a scaling factor for the Density Independent Pixel unit, where one DIP is one pixel on an approximately 160 dpi screen (for example a 240×320, 1.5″x2″ screen), providing the baseline of the system’s display. Thus on a 160dpi screen this density value will be 1; on a 120 dpi screen it would be .75; etc.

This value does not exactly follow the real screen size (as given by xdpi and ydpi, but rather is used to scale the size of the overall UI in steps based on gross changes in the display dpi. For example, a 240×320 screen will have a density of 1 even if its width is 1.8″, 1.3″, etc. However, if the screen resolution is increased to 320×480 but the screen size remained 1.5″x2″ then the density would be increased (probably to 1.5).

Читайте также:  Android mount cache as sd card

Источник

How do I get the ScreenSize programmatically in android

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?

15 Answers 15

Copy and paste this code into your Activity and when it is executed it will Toast the device’s screen size category.

Determine Screen Size :

Determine density:

I think it is a pretty straight forward simple piece of code!

This method now can be used anywhere independently. Wherever you want to get information about device screen do it as follows:

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! 🙂

You can get display size in pixels using this code.

Ways to get DisplayMetrics:

  1. val dm = DisplayMetrics() val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager wm..defaultDisplay.getMetrics(dm)

The screen density expressed as dots-per-inch. May be either DENSITY_LOW, DENSITY_MEDIUM, or DENSITY_HIGH

The absolute height of the available display size in pixels.

The absolute width of the available display size in pixels.

The exact physical pixels per inch of the screen in the X dimension.

The exact physical pixels per inch of the screen in the Y dimension.

You can try this , It is working Example

With decorations (including button bar):

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

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.

And a simple XML file

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.

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.

Источник

Get screen width and height in Android

How can I get the screen width and height and use this value in:

33 Answers 33

Using this code, you can get the runtime display’s width & height:

In a view you need to do something like this:

In some scenarios, where devices have a navigation bar, you have to check at runtime:

If the device has a navigation bar, then count its height:

So the final height of the device is:

There is a very simple answer and without pass context

Note: if you want the height include navigation bar, use method below

Читайте также:  Прошивка андроид для виндовс фон

Just to update the answer by parag and SpK to align with current SDK backward compatibility from deprecated methods:

DisplayMetrics displaymetrics = getResources().getDisplayMetrics();

It’s very easy to get in Android:

• Kotlin Version via Extension Property

If you want to know the size of the screen in pixels as well as dp , using these extension properties really helps:

DimensionUtils.kt

Usage:

Result:

When the device is in portrait orientation:

When the device is in landscape orientation:

1.

2.

3.

For kotlin user’s

And in Activity you could use it like

Get the value of screen width and height.

None of the answers here work correctly for Chrome OS multiple displays, or soon-to-come Foldables.

When looking for the current configuration, always use the configuration from your current activity in getResources().getConfiguration() . Do not use the configuration from your background activity or the one from the system resource. The background activity does not have a size, and the system’s configuration may contain multiple windows with conflicting sizes and orientations, so no usable data can be extracted.

So the answer is

As an android official document said for the default display use Context#getDisplay() because this method was deprecated in API level 30.

This code given below is in kotlin and is written accodring to the latest version of Android help you determine width and height:

You can get width and height from context

java:

kotlin

Full way to do it, that returns the true resolution:

And since this can change on different orientation, here’s a solution (in Kotlin), to get it right no matter the orientation:

I use the following code to get the screen dimensions

Methods shown here are deprecated/outdated but this is still working.Require API 13

As an android official document said for the default display use Context#getDisplay() because this method was deprecated in API level 30.

This bowl of code help to determine width and height.

Try this code for Kotlin

As getMetrics and getRealMetrics are deprecated, Google recommends to determine the screen width and height as follows:

However, I’ve figured out another methode that gives me the same results:

This is an extension function and you can use in your activity in this way:

Just use the function below that returns width and height of the screen size as an array of integers

On your onCreate function or button click add the following code to output the screen sizes as shown below

I updated answer for Kotlin language!

For Kotlin: You should call Window Manager and get metrics. After that easy way.

How can we use it effectively in independent activity way with Kotlin language?

Here, I created a method in general Kotlin class. You can use it in all activities.

Seems like all these answers fail for my Galaxy M51 with Android 11. After doing some research around I found this code :

shows my true device resolution of 1080×2400, the rest only return 810×1800.

I found weigan‘s answer best one in this page, here is how you can use that in Xamarin.Android :

Screen resolution is total no of pixel in screen. Following program will extract the screen resolution of the device. It will print screen width and height. Those values are in pixel.

this may be not work in some case. for the getMetrics comments:

Gets display metrics that describe the size and density of this display. The size returned by this method does not necessarily represent the actual raw size (native resolution) of the display.

The returned size may be adjusted to exclude certain system decor elements that are always visible.

It may be scaled to provide compatibility with older applications that were originally designed for smaller displays.

It can be different depending on the WindowManager to which the display belongs.

Источник

Экран

Небольшая подборка различных примеров для работы с экраном. На самом деле их не так часто приходится использовать в практике, но иметь общее представление бывает необходимым. Начало было положено в 2012 году, что-то могло устареть.

Читайте также:  Строить парк аттракционов андроид

Настройки — Экран

Чтобы показать окно Экран из системного приложения Настройки:

Размеры экрана и его ориентация (Старый и новый способ)

Чтобы узнать размеры экрана и его ориентацию из запущенного приложения, можно воспользоваться встроенными классами Android.

Данный способ был опубликован в те времена, когда у меня был Android 2.3. Читатели подсказали, что теперь методы считаются устаревшими (API 13 и выше). Пришлось переписывать код. Впрочем, спустя некоторое время и этот код стал считаться устаревшим.

Ориентацию при помощи нового метода не узнаешь. Помните, что это размеры экрана устройства, а не экрана вашего приложения. Кроме того, в документации как-то туманно описывается точность вычислений этих размеров. Никому верить нельзя.

Плотность экрана, масштабирование шрифта и др.

Существует класс DisplayMetrics, также имеющий в своём составе свойства для экрана. Пример также пришлось переписывать после выхода Android 11 (API 30), который теперь тоже устаревший:

Вот ещё несколько способов определения размеров:

Такой же код, но с использованием дополнительной константы SCREENLAYOUT_SIZE_MASK:

На Kotlin в виде отдельной функции.

Заглянув в документацию, обнаружил, что можно обойтись без собственных констант. Они уже есть в Android. Оформил в виде отдельного метода.

Получить текущее значение яркости экрана

В настройках экрана можно установить желаемую яркость экрана при помощи ползунка, но при этом мы не знаем, сколько это в попугаях. Я открою вам секрет при помощи простого кода:

Установить яркость экрана

Если можно получить значение текущей яркости экрана, значит можно и установить яркость. Для начала нужно установить разрешение на изменение настроек в манифесте:

Для настройки яркости нужно использовать параметр System.SCREEN_BRIGHTNESS. Добавим на форму кнопку, метку и ползунок. Код для установки яркости:

Проверил старый пример времён Android 2.2 на эмуляторе с Android 10. Правила ужесточились. Теперь разрешение на изменение системных настроек выдаются только системным программам. Пока ещё есть лазейка, которой и воспользуемся. Новый пример написан на Kotlin. Добавим в манифест немного модифицированное разрешение.

Далее программа должна проверить возможность изменять системные настройки через метод canWrite(). Если такая возможность есть, то запрашиваем разрешение. Появится специальное окно, в котором пользователь должен подтвердить своё решение через переключатель. После этого нужно заново запустить программу, чтобы ползунок стал доступен. Теперь можете менять настройки.

Настраиваем яркость экрана в своём приложении

Существует возможность переопределить яркость экрана в пределах своего приложения. Я не смог придумать, где можно найти практическое применение, но вдруг вам пригодится. Для управления яркостью экрана воспользуемся элементом SeekBar.

За яркость экрана отвечает свойство LayoutParams.screenBrightness:

Интересно, что когда выводил ползунок в значение 0, то эмулятор зависал с экраном блокировки. Вам следует учесть эту ситуацию и добавить условие:

Опять столкнулся с проблемой. Пример работал на старых устройствах, а на некоторых устройства не работает. Но за эти годы мне ни разу не пришлось использовать этот способ, поэтому даже не стал искать причину. И кстати, ошибка со значением 0 уже не возникает (возможно из-за того, что сам пример не работает как раньше).

Определение поддерживаемых экранных размеров в манифесте

Не всегда предоставляется возможным написать приложение для всех возможных типов экранов. Вы можете использовать тег в манифесте, чтобы указать, на устройствах с какими экранами может работать ваша программа.

В данном примере приводится поддержка нормальных и больших экранов. Маленьким экраном можно назвать любой дисплей с разрешением меньше, чем HVGA. Под большим экраном подразумевается такой, который значительно больше, чем у смартфона (например, у планшетов). Экран нормальных размеров имеет большинство смартфонов.

Атрибут anyDensity говорит о том, каким образом ваше приложение будет масштабироваться при отображении на устройствах с разной плотностью пикселов. Если вы учитываете это свойство экрана в своем интерфейсе, установите этому атрибуту значение true. При значении false Android будет использовать режим совместимости, пытаясь корректно масштабировать пользовательский интерфейс приложения. Как правило, это снижает качество изображения и приводит к артефактам при масштабировании. Для приложений, собранных с помощью SDK с API level 4 и выше, этот атрибут по умолчанию имеет значение true.

Размеры картинок для фона экрана

Если вы используете изображение в качестве фона, то нет смысла выводить очень большую картинку на устройстве с маленьким экраном. Можно подготовить разные размеры.

res/drawable-ldpi — 240×320
res/drawable-mdpi — 320×480
res/drawable-hdpi — 480×800
res/drawable-xhdpi — 640×960
res/drawable-xxhdpi — 960×1440
res/drawable-tvdpi — 1.33 * mdpi

Источник

Оцените статью