- Экран
- Настройки — Экран
- Размеры экрана и его ориентация (Старый и новый способ)
- Плотность экрана, масштабирование шрифта и др.
- Получить текущее значение яркости экрана
- Установить яркость экрана
- Настраиваем яркость экрана в своём приложении
- Определение поддерживаемых экранных размеров в манифесте
- Размеры картинок для фона экрана
- How to adjust screen brightness and sleep settings on Android
- How to adjust your screen brightness on Android
- How to turn off Adaptive brightness on Android
- How to turn on Ambient display on Android
- How to change the sleep settings on Android
- Qualcomm announces its new flagship Snapdragon 8 Gen 1 mobile platform
- PlayStation recap: Skyrim gets yet another re-release for its anniversary
- December Quest v35 update finally adds cloud saves and multi-user support
- These are the best cases for the Samsung Galaxy Z Flip 3 smartphone
- Changing the Screen Brightness System Setting Android
- 4 Answers 4
- How to Maximize/Minimize Screen Brightness Programmatically in Android?
- Where can we use this feature?
- Approach
Экран
Небольшая подборка различных примеров для работы с экраном. На самом деле их не так часто приходится использовать в практике, но иметь общее представление бывает необходимым. Начало было положено в 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
Источник
How to adjust screen brightness and sleep settings on Android
On top of changing your phone’s brightness, you can also customize the sleep settings, which allows you to choose how long it takes for your screen to shut when you’re not using it. Here’s how to adjust your brightness and sleep settings.
How to adjust your screen brightness on Android
- Swipe down from the top of the screen to reveal the Notification Shade. Depending on which Android phone you have, you may have to swipe twice.
- Tap and hold the brightness slider. It’s the icon that looks like the sun.
- Drag the brightness slider to your desired brightness.
Release the slider.
How to turn off Adaptive brightness on Android
Adaptive brightness gives your phone the ability to adjust the screen brightness automatically depending on the amount of light around you. The setting is typically on by default, but it’s easy to turn off if you want to.
- Swipe down from the top of the screen to reveal the Notification Shade. Depending on which Android phone you have, you may have to swipe twice.
Tap on the settings button. It’s the gear icon in the top right.
Tap the On/Off switch beside Adaptive brightness.
You can follow these exact steps to turn the adaptive brightness setting back on whenever you need.
How to turn on Ambient display on Android
Enabling Ambient display allows you to view the time and notifications on your lock screen without having to press the power or home buttons.
- Swipe down from the top of the screen to reveal the Notification Shade. Depending on which Android phone you have, you may have to swipe twice.
Tap on the settings button. It’s the gear icon in the top right.
Tap the On/Off switch beside Ambient display.
Follow the same steps to turn off Ambient display whenever you want.
How to change the sleep settings on Android
- Swipe down from the top of the screen to reveal the Notification Shade. Depending on which Android phone you have, you may have to swipe twice.
- Tap on the settings button. It’s the gear icon in the top right.
Tap Display.
Tap the amount of time you want. Your options are as follows:
- 15 seconds
- 30 seconds
- 1 minute
- 2 minutes
- 5 minutes
- 10 minutes
Qualcomm announces its new flagship Snapdragon 8 Gen 1 mobile platform
Qualcomm launches its latest flagship Snapdragon chipset to power the best Android phones of 2022. The new chip features improvements in AI, imaging, gaming, and more.
PlayStation recap: Skyrim gets yet another re-release for its anniversary
Don’t miss out on any PlayStation news that happened in November. We’ve rounded up the biggest stories for you to check out, like Skyrim’s re-release and Elden Ring’s tech test.
December Quest v35 update finally adds cloud saves and multi-user support
The December v35 update is now rolling out for the Oculus Quest and Meta Quest 2, bringing half a dozen new features along with it.
These are the best cases for the Samsung Galaxy Z Flip 3 smartphone
The Galaxy Z Flip 3 exists in more colors than you could imagine. You should show off and protect those colors with a quality case. These are the best cases from Samsung, Spigen, Incipio, and beyond.
Источник
Changing the Screen Brightness System Setting Android
I’m attempting to change the screen brightness from withing a service, like so:
Problem is that is doesn’t work. Well, actually it succeeds in changing the brightness setting, but the screen brightness doesn’t actually change till I go into the phones settings, look at the new value and hit Ok.
Is there something I have to do after setting the value to get the brightness to change?
4 Answers 4
I’ve had the same problem of changing screen brightness from within a service, and a couple days ago i have successfully solved it(and updated my app Phone Schedule with brightness feature 😉 ). Ok, so this is the code you put into your service:
Please Note that in the above code snippet I’m using two variables for brightness. One is brightness , which is a float number between 0.0 and 1.0, the other one is brightnessInt , which is an integer between 0 and 255. The reason for this is that Settings.System requires an integer to store system wide brightness value, while the lp.screenBrightness which you will see in the next code snippet requires a float. Don’t ask me why not use the same value, this is just the way it is in Android SDK, so we’re just going to have to live with it.
This is the code for DummyBrightnessActivity:
This is how you add your activity to the AndroidManifest.xml, probably the most important part:
A little explanation about what’s what.
android:taskAffinity must be different, than your package name! It makes DummyBrightnessActivity be started not in your main stack of activities, but in a separate, which means that when DummyBrightnessActivity is closed, you won’t see the next activity, whatever that may be. Until i included this line, closing DummyBrightnessActivity would bring up my main activity.
android:excludeFromRecents=»true» makes this activity not available in the list of recently launched apps, which you definetely want.
android:theme=»@style/EmptyActivity» defines the way DummyBrightnessActivity looks like to the user, and this is where you make it invisible. This is how you define this style in the styles.xml file:
This way your DummyBrightnessActivity will be invisible to the user. I’m not shure if all of those style parameters are really necessary, but it works for me this way.
I hope that explains it, but if you have any questions, just let me know.
Источник
How to Maximize/Minimize Screen Brightness Programmatically in Android?
Screen brightness is one such factor that directly affects the users as well as the battery on a device. Android devices are Smart systems and have an inbuilt system for Auto-Brightness. But mostly this feature is unchecked by the users or set off by default. Irrespective of whether this feature is present, set on or off, or absent in any device, a developer must take this opportunity into consideration and develop an optimized application. Anything that is declared inside the application might have an effect on the outside space, i.e., if the screen brightness was changed programmatically from an application, the brightness value might stay unaltered even after exiting the application. So one must try to trace back the originals and set them before a user exits.
Where can we use this feature?
- Applications Streaming Videos: Each frame could be analyzed and compared with the ambient light of the room and accordingly make changes while viewing it to the users.
- Low Battery Situations: Brightness can be set at a low value if the battery level is low.
- If the screen is inactive or unresponded: If the screen is inactive or unresponded, the brightness could be lowered after a specific time-out.
A sample GIF is given below to get an idea about what we are going to do in this article . Note that we are going to implement this project using the Kotlin language.
Approach
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Источник