Display method in android

Экран

Небольшая подборка различных примеров для работы с экраном. На самом деле их не так часто приходится использовать в практике, но иметь общее представление бывает необходимым. Начало было положено в 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.

Читайте также:  Как узнать сколько bit андроид

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

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

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

Источник

Display Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Provides information about the size and density of a logical display.

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

A constructor used when creating managed representations of JNI objects; called by the runtime.

Fields

The default Display id, which is the id of the primary display assuming there is one.

Display flag: Indicates that the display is a presentation display.

Display flag: Indicates that the display is private.

Display flag: Indicates that the display has a round shape.

Display flag: Indicates that the display has a secure video output and supports compositing secure surfaces.

Display flag: Indicates that the display supports compositing content that is stored in protected graphics buffers.

Invalid display id.

Properties

Gets the app VSYNC offset, in nanoseconds.

Returns the runtime class of this Object .

(Inherited from Object) Cutout

Returns the DisplayCutout , or null if there is none.

Returns the product-specific information about the display or the directly connected device on the display chain.

Gets the display id.

Returns a combination of flags that describe the capabilities of the display.

The handle to the underlying Android instance.

(Inherited from Object) Height IsHdr

Returns whether this display supports any HDR type.

Returns true if the connected display can be switched into a mode with minimal post processing.

Returns true if this display is still valid, false if the display has been removed.

Returns whether this display can be used to display wide color gamut content.

Gets the name of the display.

Gets the pixel format of the display.

Returns the preferred wide color space of the Display.

This is how far in advance a buffer must be queued for presentation at a given time.

Gets the refresh rate of this display in frames per second.

Returns the rotation of the screen from its «natural» orientation.

Gets the state of the display, such as whether it is on or off.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Creates and returns a copy of this object.

(Inherited from Object) Dispose() (Inherited from Object) Dispose(Boolean) (Inherited from Object) Equals(Object)

Indicates whether some other object is «equal to» this one.

(Inherited from Object) GetCurrentSizeRange(Point, Point)

Return the range of display sizes an application can expect to encounter under normal operation, as long as there is no physical change in screen size.

Returns a hash code value for the object.

(Inherited from Object) GetHdrCapabilities()

Returns the display’s HDR capabilities.

Gets display metrics that describe the size and density of this display.

Returns the active mode of the display.

Gets the size of the largest region of the display accessible to an app in the current system state, without subtracting any window decor or applying scaling factors.

Gets the size of the largest region of the display accessible to an app in the current system state, without subtracting any window decor or applying scaling factors.

Gets the size of the display as a rectangle, in pixels.

Returns the RoundedCorner of the given position if there is one.

Gets the size of the display, in pixels.

Gets the supported modes of this display.

Get the supported refresh rates of this display in frames per second.

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

(Inherited from Object) Notify()

Wakes up a single thread that is waiting on this object’s monitor.

(Inherited from Object) NotifyAll()

Wakes up all threads that are waiting on this object’s monitor.

(Inherited from Object) SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Object) ToArray () (Inherited from Object) ToString()

Returns a string representation of the object.

(Inherited from Object) UnregisterFromRuntime() (Inherited from Object) Wait()

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

Читайте также:  Диспетчер файлов для андроид как найти

(Inherited from Object) Wait(Int64)

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object) Wait(Int64, Int32)

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

InputMethodManager

java.lang.Object
android.view.inputmethod.InputMethodManager

Class Overview

Central system API to the overall input method framework (IMF) architecture, which arbitrates interaction between applications and the current input method. You can retrieve an instance of this interface with Context.getSystemService() .

Architecture Overview

There are three primary parties involved in the input method framework (IMF) architecture:

  • The input method manager as expressed by this class is the central point of the system that manages interaction between all other parts. It is expressed as the client-side API here which exists in each application context and communicates with a global system service that manages the interaction across all processes.
  • An input method (IME) implements a particular interaction model allowing the user to generate text. The system binds to the current input method that is use, causing it to be created and run, and tells it when to hide and show its UI. Only one IME is running at a time.
  • Multiple client applications arbitrate with the input method manager for input focus and control over the state of the IME. Only one such client is ever active (working with the IME) at a time.

Applications

In most cases, applications that are using the standard TextView or its subclasses will have little they need to do to work well with soft input methods. The main things you need to be aware of are:

  • Properly set the inputType in your editable text views, so that the input method will have enough context to help the user in entering text into them.
  • Deal well with losing screen space when the input method is displayed. Ideally an application should handle its window being resized smaller, but it can rely on the system performing panning of the window if needed. You should set the windowSoftInputMode attribute on your activity or the corresponding values on windows you create to help the system determine whether to pan or resize (it will try to determine this automatically but may get it wrong).
  • You can also control the preferred soft input state (open, closed, etc) for your window using the same windowSoftInputMode attribute.

More finer-grained control is available through the APIs here to directly interact with the IMF and its IME — either showing or hiding the input area, letting the user pick an input method, etc.

For the rare people amongst us writing their own text editors, you will need to implement onCreateInputConnection(EditorInfo) to return a new instance of your own InputConnection interface allowing the IME to interact with your editor.

Input Methods

An input method (IME) is implemented as a Service , typically deriving from InputMethodService . It must provide the core InputMethod interface, though this is normally handled by InputMethodService and implementors will only need to deal with the higher-level API there.

See the InputMethodService class for more information on implementing IMEs.

Security

There are a lot of security issues associated with input methods, since they essentially have freedom to completely drive the UI and monitor everything the user enters. The Android input method framework also allows arbitrary third party IMEs, so care must be taken to restrict their selection and interactions.

Here are some key points about the security architecture behind the IMF:

Only the system is allowed to directly access an IME’s InputMethod interface, via the BIND_INPUT_METHOD permission. This is enforced in the system by not binding to an input method service that does not require this permission, so the system can guarantee no other untrusted clients are accessing the current input method outside of its control.

There may be many client processes of the IMF, but only one may be active at a time. The inactive clients can not interact with key parts of the IMF through the mechanisms described below.

Clients of an input method are only given access to its InputMethodSession interface. One instance of this interface is created for each client, and only calls from the session associated with the active client will be processed by the current IME. This is enforced by AbstractInputMethodService for normal IMEs, but must be explicitly handled by an IME that is customizing the raw InputMethodSession implementation.

Читайте также:  Скачивание с контакта для андроид

Only the active client’s InputConnection will accept operations. The IMF tells each client process whether it is active, and the framework enforces that in inactive processes calls on to the current InputConnection will be ignored. This ensures that the current IME can only deliver events and text edits to the UI that the user sees as being in focus.

An IME can never interact with an InputConnection while the screen is off. This is enforced by making all clients inactive while the screen is off, and prevents bad IMEs from driving the UI when the user can not be aware of its behavior.

A client application can ask that the system let the user pick a new IME, but can not programmatically switch to one itself. This avoids malicious applications from switching the user to their own IME, which remains running when the user navigates away to another application. An IME, on the other hand, is allowed to programmatically switch the system to another IME, since it already has full control of user input.

The user must explicitly enable a new IME in settings before they can switch to it, to confirm with the system that they know about it and want to make it available for use.

Summary

Constants
int HIDE_IMPLICIT_ONLY Flag for hideSoftInputFromWindow(IBinder, int) to indicate that the soft input window should only be hidden if it was not explicitly shown by the user.
int HIDE_NOT_ALWAYS Flag for hideSoftInputFromWindow(IBinder, int) to indicate that the soft input window should normally be hidden, unless it was originally shown with SHOW_FORCED .
int RESULT_HIDDEN Flag for the ResultReceiver result code from showSoftInput(View, int, ResultReceiver) and hideSoftInputFromWindow(IBinder, int, ResultReceiver) : the state of the soft input window changed from shown to hidden.
int RESULT_SHOWN Flag for the ResultReceiver result code from showSoftInput(View, int, ResultReceiver) and hideSoftInputFromWindow(IBinder, int, ResultReceiver) : the state of the soft input window changed from hidden to shown.
int RESULT_UNCHANGED_HIDDEN Flag for the ResultReceiver result code from showSoftInput(View, int, ResultReceiver) and hideSoftInputFromWindow(IBinder, int, ResultReceiver) : the state of the soft input window was unchanged and remains hidden.
int RESULT_UNCHANGED_SHOWN Flag for the ResultReceiver result code from showSoftInput(View, int, ResultReceiver) and hideSoftInputFromWindow(IBinder, int, ResultReceiver) : the state of the soft input window was unchanged and remains shown.
int SHOW_FORCED Flag for showSoftInput(View, int) to indicate that the user has forced the input method open (such as by long-pressing menu) so it should not be closed until they explicitly do so.
int SHOW_IMPLICIT Flag for showSoftInput(View, int) to indicate that this is an implicit request to show the input window, not as the result of a direct request by the user.
Public Methods

Constants

public static final int HIDE_IMPLICIT_ONLY

Flag for hideSoftInputFromWindow(IBinder, int) to indicate that the soft input window should only be hidden if it was not explicitly shown by the user.

public static final int HIDE_NOT_ALWAYS

Flag for hideSoftInputFromWindow(IBinder, int) to indicate that the soft input window should normally be hidden, unless it was originally shown with SHOW_FORCED .

public static final int RESULT_HIDDEN

Flag for the ResultReceiver result code from showSoftInput(View, int, ResultReceiver) and hideSoftInputFromWindow(IBinder, int, ResultReceiver) : the state of the soft input window changed from shown to hidden.

public static final int RESULT_SHOWN

Flag for the ResultReceiver result code from showSoftInput(View, int, ResultReceiver) and hideSoftInputFromWindow(IBinder, int, ResultReceiver) : the state of the soft input window changed from hidden to shown.

public static final int RESULT_UNCHANGED_HIDDEN

Flag for the ResultReceiver result code from showSoftInput(View, int, ResultReceiver) and hideSoftInputFromWindow(IBinder, int, ResultReceiver) : the state of the soft input window was unchanged and remains hidden.

public static final int RESULT_UNCHANGED_SHOWN

Flag for the ResultReceiver result code from showSoftInput(View, int, ResultReceiver) and hideSoftInputFromWindow(IBinder, int, ResultReceiver) : the state of the soft input window was unchanged and remains shown.

public static final int SHOW_FORCED

Flag for showSoftInput(View, int) to indicate that the user has forced the input method open (such as by long-pressing menu) so it should not be closed until they explicitly do so.

public static final int SHOW_IMPLICIT

Flag for showSoftInput(View, int) to indicate that this is an implicit request to show the input window, not as the result of a direct request by the user. The window may not be shown in this case.

Public Methods

public void displayCompletions (View view, CompletionInfo[] completions)

public InputMethodSubtype getCurrentInputMethodSubtype ()

Returns the current input method subtype. This subtype is one of the subtypes in the current input method. This method returns null when the current input method doesn’t have any input method subtype.

public List getEnabledInputMethodList ()

public List getEnabledInputMethodSubtypeList (InputMethodInfo imi, boolean allowsImplicitlySelectedSubtypes)

Returns a list of enabled input method subtypes for the specified input method info.

Источник

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