Android wake lock permissions

Keeping your Android application running when the device wants to sleep (Updated for Android Pie)

Updated January 2020 to include detail about Android Pie.

Since the introduction of doze mode in Android Marshmallow we have seen a number of enterprise use cases where customers want to ensure their application continues to run even though the device wants to enter a power saving mode. It is assumed the reader is familiar with doze mode and the other changes made in Android Oreo and Pie related to background services, at least at a high level.

From a consumer point of view, getting maximum battery life out of a device is frequently an ever-present consideration, so much so that a slew of snake oil “task manager” and “task killer” applications formerly gained popularity to prevent background apps but in recent Android releases Google has taken a more aggressive approach to what apps can do in the background.

Enterprise applications are written primarily to enhance user efficiency; battery consumption will always be a consideration but may be secondary or tertiary to application responsiveness or performance.

The goal of this blog is to explain your options as an application developer to give you the most control over your device’s power management and what you can do to ensure your application is always available to your users.

There are two fundamental reasons people might not want the device to enter a power saving mode:

  • The application should be available to respond to network requests, for example a push message. Often Firebase Cloud Messaging (FCM) is not a suitable option for customers because the device is behind a firewall or does not have GMS services available.
  • The application needs to do work continually and it is not acceptable for the Android OS to kill the application’s background services.

Before diving into the detail, it is necessary to understand the concepts around Android power management:

Wake Locks

Wake locks are an Android concept designed to allow an application to indicate that it wants to have the device stay on, for example the YouTube application would take a FULL_WAKE_LOCK to prevent the screen turning off whilst the user is watching a video. A wake lock can control the status of the CPU, Screen and hardware Keyboard backlight but all but one type of wake lock can be cancelled by the end user simply by pressing the power key. Since only PARTIAL_WAKE_LOCKs persist when the user presses the power key the remainder of this blog will be concerned exclusively with those, where the CPU continues running but the screen and hardware keyboard backlight is allowed to turn off.

Android documentation is available for the wake lock definition as well as methods to acquire and release wake locks.

Any application requiring a wake lock must request the android permission:

You can detect any wake locks being held by applications on your device through adb:

The following screenshot shows a single wake lock is on the device, it is a partial wake lock and has been given the tag ‘WakeLockExampleAppTag1’ by the application which created it:

Читайте также:  Управление с андроида линукс

Wake lock acquired.png

Partial wake locks will be released either when the application which created it calls release(), or the lock was only acquired for a specified time. Note that wake locks will be automatically released when the device enters doze mode unless battery optimization is disabled for the application which acquired the lock (see later)

Whilst this blog is concerned primarily with Android Marshmallow, you may notice that earlier Zebra devices’ WiFi service gains its own partial wake lock, even when the WiFi policy is set to not «keep WiFi awake when the device is sleeping». You can see any wake lock using the technique described above and should bear this in mind if wondering why your device is not sleeping when expected on earlier devices e.g. MC40.

WiFi Locks

WiFi locks are only applicable to Android Nougat devices and below (Marshmallow, Lollipop etc). From Android Oreo onward the WiFi will always be on when the device is sleeping.

WiFi locks allow an application to keep the WLAN radio awake when the user has not used the device in a while, they are frequently used in conjunction with wake locks since any application doing work in the background would likely need WLAN connectivity (e.g. downloading a large file)

Android documentation for the WifiLock is here and the documentation on how to acquire a WiFi lock is here.

As stated in the official docs, WifiLocks cannot override the user-level “Wifi-Enabled” setting, nor Airplane Mode. For Zebra devices, we can extend this to WifiLocks not being able to override the Wi-Fi Enable / Disable setting of the WiFi CSP

Some other special considerations for Zebra devices:

  • Out of the box, older Zebra devices come pre-loaded with the AppGallery client. AppGallery will be holding its own WifiLock lock and since the radio is only allowed to turn off when no WifiLocks are held, the radio will not turn off by default (until the device enters doze mode). AppGallery’s lock is defined as follows:
    • WifiLock
  • You can disable AppGallery in a number of ways:
    • Using the MX AccessManager whitelist feature
    • Using the MX ApplicationManager to disable the application
    • Using Enterprise Home Screen’s preference
    • Disabling the application manually under Settings —> Apps —> AppGallery —> App info

Note that the current package name is com.rhomobile.appgallery but that may change in the future.

  • Zebra devices also have an additional “Sleep Policy” parameter as part of the MX Wifi Manager
    • You can set the sleep policy via the Settings UI: Settings —> Wi-Fi —> (Menu) Advanced —> “Keep Wi-Fi on during sleep”. The values are:
      • Always (the WiFi radio will not turn off when the device sleeps)
      • ‘Only when plugged in’ (the WiFi radio will not turn off provided the device is connected to power)
      • Never (the WiFi radio will be allowed to turn off when the device sleeps)
    • The sleep policy does not hold a separate WiFi lock, it is configuring the WiFi policy and is reflected in the mSleepPolicy value.
    • The default value of the sleep policy will vary from device to device. As a general rule, devices running Marshmallow or earlier will have this value set to ‘Never’ and devices running Nougat or later will set this value to ‘Always’ but there will be exceptions (notably the TC8000, a Lollipop device, defaults to ‘Always’).
      • For a consistent staging experience across all devices it is recommended to use StageNow’s WifiSleepPolicy parameter
    • The device will only turn WiFi off during standby if there are no WiFi locks and it is allowed to do so according to the WiFi sleep policy
  • When the device receives a network request over WiFi, the device obviously needs to do some processing to handle the message. Although this requires hardware support from the WiFi stack and processor, recent Zebra devices will be able to wake the processor to perform the required packet handling. If more than simple processing is required when packets are received it may be prudent to also acquire a wake lock for the duration of that processing. This is true of all Android Marshmallow or later devices.
Читайте также:  What is form data on android

You can detect any wifi locks being held by applications on your device through adb:

The following screenshot shows a single wifi lock is on the device (in blue) and is given the tag ‘WifiLockExampleAppTag1’ by the application which created it. Highlighted in green is the mSleepPolicy variable which can be used to determine the WiFi sleep policy, here 0 is ‘Never’ keep WiFi on during sleep but a value of 2 would indicate ‘Always’ keep WiFi on during sleep.:

Источник

Какая польза от разрешения Android Wake Lock?

Когда и зачем использовать разрешение android . Просьба представить образец кода, касающегося блокировки слежения.

Вы можете использовать wakelock для включения экрана – вы можете увидеть пример в этом коде .

Если вам нужна дополнительная информация, вы должны указать свой вопрос.

WakeLock – это механизм для включения устройства, как написано здесь и здесь.

Он используется, например, когда вам нужно что-то делать, даже когда устройство, похоже, спит, например, загружает файлы из Интернета.

Вакелокс никогда не следует использовать, если вы им в действительности не нужны. Причина в том, что они потребляют больше батареи, и если у вас есть ошибка, которая не будет выпускать их при необходимости, ваше приложение будет продолжать потреблять батарею устройства. Есть даже приложения для обнаружения таких проблемных приложений (например, «детектор вакелока»).

Кроме того, небольшой совет для людей, которые просто хотят, чтобы экран оставался (пока отображается приложение): вам не нужно (и вам не нужно) разрешение wakeLock. Вместо этого вы должны просто установить « android:keepScreenOn=»true» » в макете текущей активности. Подробнее об этом говорят на лекции «Кодирование жизни – срок службы батареи, то есть» (презентация здесь )

Блокировка следа – это механизм, указывающий на то, что ваше приложение должно оставаться включенным.

Любое приложение, использующее WakeLock должно запрашивать разрешение android.permission.WAKE_LOCK в элементе манифеста приложения. Получите блокировку newWakeLock(int, String) вызвав newWakeLock(int, String) .

Пробуждение устройства, когда его сон, т.е. когда пользователь не присутствует в режиме блокировки экрана

Источник

Русские Блоги

Wakelock для анализа энергопотребления Android

Жизнь всегда оставляет нас в синяках и синяках, но в будущем эти травмированные места обязательно станут нашими сильнейшими местами. — Хемингуэй

Что такое WakeLock

WakeLock — это набор механизмов, предоставляемых уровнем инфраструктуры Android, которые могут использоваться приложениями для управления состоянием устройств Android. Состояние устройства здесь в основном относится к открытию и закрытию экрана, а также к продолжению работы процессора. Просто поймите, что WakeLock — это средство, чтобы система не спала.

Функция WakeLock

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

Читайте также:  Windows launcher для андроид без рекламы

Какие бывают категории WakeLock

WakeLock — это внутренний класс PowerManager, путь к которому находится по адресу:

WakeLock классифицируется следующим образом:

  • PARTIAL_WAKE_LOCK: экран выключен, и ЦП продолжает работать, когда подсветка клавиатуры выключена.
  • PROXIMITY_SCREEN_OFF_WAKE_LOCK: отключение экрана на основе датчика приближения. Наиболее типичный сценарий приложения — когда мы звоним по телефону близко к ушам, экран автоматически выключается.
  • SCREEN_DIM_WAKE_LOCK / SCREEN_BRIGHT_WAKE_LOCK / FULL_WAKE_LOCK: эти три типа WakeLock устарели. Их цель — сохранить яркость экрана. Официальный представитель Android рекомендует использовать getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); Способ замены. Поскольку этот метод проще, чем применение WakeLock, и не требуется специального приложения. android.permission.WAKE_LOCK Разрешения.
  • DOZE_WAKE_LOCK / DRAW_WAKE_LOCK: скрытые категории, используются только на системном уровне.

Флаг WakeLock выглядит следующим образом:

  • ACQUIRE_CAUSES_WAKEUP: включить экран, например, экран включается после того, как приложение получает уведомление.
  • ON_AFTER_RELEASE: после выхода WakeLock экран не выключается сразу.
  • UNIMPORTANT_FOR_LOGGING: скрытый флаг, используется только на системном уровне.

Процесс установки WakeLock

WakeLock выполняет операцию настройки из пользовательского пространства, затем входит в пространство ядра и, наконец, записывает в /sys/power/wake_lock Файловый узел.
Давайте проследим процесс получения WakeLock с точки зрения исходного кода.

hardware/libhardware_legacy/power/power.c
collect_wake_lock и, наконец, записать wakelock в узел в этом методе

Использование WakeLock

К использованию WakeLock следует обращаться осторожно. Неправильное использование может сделать приложение «убийцей батареи». Используемые принципы

  1. Постарайтесь не использовать его, если вы им не пользуетесь: например, если вы хотите, чтобы экран оставался ярким, вам следует использовать его. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); Способ.

PowerManager.FULL_WAKE_LOCK будет держать экран включенным в течение длительного времени, например, установив автоматическое выключение экрана на 15 секунд. После применения wakelock экран не выключится, даже если он превышает 15 секунд. Но если пользователь активно нажимает кнопку питания, экран все равно будет выключен.

  1. Если вам нужно его использовать, не забудьте освободить его после использования.
    Есть два способа подать заявку на WakeLock: получить () и получить (длительный тайм-аут). Последний относительно безопаснее. Если вы забудете освободить WakeLock, система автоматически отключится по истечении тайм-аута. .

Типичное использование WakeLock выглядит следующим образом:

В то же время вам нужно добавить разрешения в файле манифеста

Методы отладки для проблем, связанных с WakeLock

Отладка на уровне приложений

Если вы просто проверяете, не срабатывает ли будильник определенного приложения ненормально, вы можете использовать команду

Для просмотра, например, в следующем примере кода

При входе в метод onResume информация dumpsys выглядит следующим образом:

Проходить PARTIAL_WAKE_LOCK ‘azhengye-test-wakelock’ ON_AFTER_RELEASE ACQ=-4m52s949ms LONG (uid=10124 pid=31473 pkg=com.azhengye.testpath) Вы можете видеть, что приложение wakelock успешно работает.
Если вы введете метод onPause, то только что запрошенный wakelock должен быть снят. В это время информация из dumpsys выглядит следующим образом:

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

Отладка системного уровня

Отладить проблемы, связанные с wakelock, на системном уровне сложнее. Основные шаги заключаются в следующем.

Согласно анализу журнала
Сначала включите переключатель отладки
frameworks/base/services/core/java/com/android/server/power/PowerManagerService.java

Затем dumpsys power view и поиск в logcat acquireWakeLockInternal Ключевое слово для просмотра статуса приложения Wakelock,
, например

ищи releaseWakeLockInternal Проверьте выпуск. lock= Следующие целые числа могут соответствовать получению и освобождению. В сочетании с меткой времени logcat вы можете получить продолжительность удержания wakelock. Кратковременное удержание wakelock обычно не вызывает проблем. Вид удержания wakelock в течение длительного времени будет увеличиваться потребляемая мощность. Есть проблема, это должно быть основано на tag Перейдите в поле кода, чтобы просмотреть конкретный процесс получения / выпуска.

После того, как система проработает какое-то время, получите отчет об ошибке. Используйте архиватор, чтобы проверить статус приложения wakelock.Вы можете проверить предыдущий блог для подробностейПостроение среды анализа энергопотребления историка батареи Android

Источник

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