Prevent android app from sleeping

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.
Читайте также:  Датчик движения для андроида

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 в спящий режим программно?

Как предотвратить устройство Android от перехода в спящий режим программно?

7 ответов:

один из вариантов-это использовать Примечание. Пример из документов:

и по на этой странице это описывает различные виды wakelocks.

имейте в виду, что некоторые меры предосторожности должны быть приняты при использовании блокировки пробуждения. Убедитесь, что вы всегда release() замок, когда вы закончите с ним (или не на переднем плане). В противном случае ваше приложение может потенциально вызвать серьезную утечку батареи и использование процессора.

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

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

если вы просто хотите, чтобы предотвратить спящий режим на определенный View , просто позвоните setKeepScreenOn(true) на View и выберите keepScreenOn свойство true . Это позволит предотвратить экран от выключения в то время как View на экране. Для этого не требуется специального разрешения.

Я нашел другое рабочее решение: добавьте следующую строку в свое приложение под событием onCreate.

мой пример проекта Cordova выглядит так:

после этого мое приложение не будет спать, пока оно было открыто. Спасибо, что anwer идет в xSus.

android:keepScreenOn=»true» может быть лучшим вариантом, чтобы иметь от макета XML.

установите флаги в окне активности, как показано ниже

из корневой оболочки (например, adb shell), вы можете заблокировать с:

после чего устройство будет бодрствовать, пока вы будете делать:

С той же строкой для ‘mylockname’.

обратите внимание, что это не помешает экрану стать черным, но это помешает процессору спать.

обратите внимание, что /sys/power/wake_lock-это чтение-запись для пользовательского радио (1001) и групповой системы (1000), и, конечно же, root.

то, что сказал @eldarerathis, правильно во всех аспектах, блокировка пробуждения-это правильный способ удержать устройство от сна.

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

Источник

Prevent android app from sleeping

Prevent the screen of the mobile device from falling asleep.

  • The device will never fall asleep after calling keepAwake .
  • After making your app practically a zombie, you can allow it to sleep again by calling allowSleepAgain .
  • Works on Android, probably every version you’d care about.
  • Works on iOS, probably every version you’d care about.
  • Works on Windows and WP8.
Читайте также:  Что такое дамп системы андроид

Automatically (CLI / Plugman)

Insomnia is compatible with Cordova Plugman and ready for the PhoneGap 2.9.0 CLI, here’s how it works with the CLI:

run this command afterwards:

The javascript bridge is brought in automatically, so no need to reference Insomnia.js from your html.

You can also get this plugin from NPM.

1. Add the following xml to your config.xml in the root directory of your www folder:

2. Grab a copy of Insomnia.js, add it to your project and reference it in index.html :

3. Download the source files for iOS and/or Android and copy them to your project.

iOS: Copy Insomnia.h and Insomnia.h to platforms/ios/

Android: Copy Insomnia.java to platforms/android/src/nl/xservices/plugins (create the folders)

wp8: Copy Insomnia.cs to platforms/wp8/Plugins/nl.x-services.plugins.insomnia (create the folders)

Insomnia works with PhoneGap build too, look for Insomnia here: https://build.phonegap.com/plugins/ Just add the following xml to your config.xml to always use the latest version of this plugin:

or to use this exact version:

The plugin’s javascript file is brought in automatically. Make sure though you include a reference to cordova.js in your index.html’s head:

An optional successCallback (first argument) will be triggered if the functions succeed. Even calling keepAwake twice will fire the successCallback, because the app will respond as expected (being kept awake).

An optional errorCallback (second argument) will only be triggered if something fatal happened, preventing the plugin to work as expected.

Note that calling allowSleepAgain without calling keepAwake first will trigger errorCallback or throw an error if not provided.

In this issue it was reported that on iOS the app would fall asleep after the Camera has been used, even if you previously called keepAwake . A similar issue on Android where the photo library was accessed during app usage.

So to make sure your app honors keepAwake you have to re-run that method after these kinds of ‘external UI’ thingies give control back to your app.

This plugin was enhanced for Plugman / PhoneGap Build by Eddy Verbruggen.

The Android code was entirely created by the author.

The iOS code was heavily inspired by Wolfgang Koller.

Many thanks to Jesse MacFadyen for implementing the wp8 and windows versions!

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About

😪 Prevent the screen of the mobile device from falling asleep

Источник

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