Android dont turn off screen

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.

Читайте также:  Six horrors 4 android

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: Как программно включать и выключать экран?

Прежде чем пометить этот пост как «дублирующий», я пишу его, потому что никакое другое сообщение не содержит решения проблемы.

Я пытаюсь выключить устройство, затем через несколько минут или смены датчика снова включаю.

Отключить тесты дисплея

Я могу выключить экран, используя:

Мне не удалось выключить экран с помощью метода wl.release ().

Включите тест дисплея

Моя первая догадка, как следует, не работает. Ничего не происходит, экран остается выключенным.

Я также попытался использовать wakelocks, но безуспешно.

Наконец, я попробовал следующее, но безрезультатно.

В общем, я не получаю никаких ошибок в консоли ни для одного из этих методов. Мой тестовый текст «Экран должен быть включен» появляется на экране, когда я включаю устройство с помощью кнопки питания. Это показывает, что код должен был работать. Пожалуйста, отвечайте только в том случае, если вы протестировали код, похоже, что многие функции, такие как params.screenBrightness = -1 , не работают должным образом согласно sdk.

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

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

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

Теперь, чтобы вернуть экран к нормальной яркости, достаточно установить значение яркости:

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

Читайте также:  Учебник по android разработке

Это определенно работает. Например, приложения Google Книги используют это, чтобы вы могли настроить яркость экрана на затемнение при использовании книги, а затем вернуться к обычной яркости при выключении.

Чтобы облегчить отладку, вы можете использовать «adb shell dumpsys window», чтобы увидеть текущее состояние вашего окна. В данных для вашего окна он сообщит вам текущие LayoutParams, которые были установлены для него. Убедитесь, что ценность, которую вы думаете, действительно существует.

И снова FLAG_KEEP_SCREEN_ON — это отдельная концепция; он и яркость не влияют друг на друга напрямую. (И не было бы причин снова устанавливать флаг при отмене яркости, если вы уже установили его при установке яркости на 0. Флаг останется установленным, пока вы его не измените.)

Источник

How to Turn Off Phone without Power Button (Android)

Nobody needs a tutorial to learn how one can turn a phone on or off. However, if the Power button or the screen of your device is broken or not functioning for some reason, you might end up looking for a guide like this. In this tutorial, we’ll be exploring all possible ways to restart and turn off an Android phone or tablet without the power button or the volume buttons. If you want to just wake up your phone’s screen and make it sleep without the power button, read my tutorial.

The power button of a phone might break or stop being responsive due to an accidental drop, overuse, mishandling, poor build quality. If you have been using your phone or tablet for many years, the power button may become non-functional. The ultimate solution to this hardware problem is to visit a service center to get it fixed. Alternatively, you can use one of the tips given below to turn off your phone without the power button. Whether you own a phone from Samsung, Xiaomi, Oppo, OnePlus, Vivo, Realme, Nokia, or any other Android device, these tips will work on all Android devices.

Turn Off Phone without Power Button

There are several ways to power off an Android phone or tablet if power the button is broken. The tips will also help you restart the phone without the power button and volume button.

  • Using an ADB command
  • Via Android Accessibility Menu
  • Using a reboot app
  • Via Quick Settings menu (Samsung devices)

Before you learn to turn off your Android device, don’t forget to check out my detailed article describing 8 ways to turn on an Android phone without the power button.

ADB Command to Turn Off Phone

I won’t say that it’s the most convenient method to turn off Android devices when the power button is broken or the screen is damaged. However, it is possible to switch off and reboot an Android phone or tablet into Safe Mode, System Mode, Bootloader Mode, or Recovery Mode using ADB commands without using the Power and Volume keys.

To be able to run ADB commands on your Android device, you’ll need a laptop or PC. One more thing, USB debugging must be enabled on your device. Anyway, let’s see how to switch off an Android phone without the Power button and volume button.

  1. Download the latest Android SDK Platform-tools for Windows, or set up ADB and Fastboot on macOS.
  2. Enable USB debugging on your Android device if you don’t have it enabled already. You might not be able to do this if your phone’s touch screen is not working.
  3. Launch the Windows Command Prompt or Mac Terminal.
  4. Connect your device to your computer via a compatible USB cable.
  5. Issue the following command to ensure that your phone and computer are connected properly.
  6. Now, execute the following ADB command to turn off your Android phone. Here, ‘p‘ stands for ‘power off’.

  • Your Android device will power off without using the Power button.
  • In case you just want to restart your phone without using the power button, you can use the following command.
  • The ADB method can allow you to switch off your phone when the touch is not working.

    ADB Command to Power Off Android via Power Menu

    ADB commands can be a great help in certain tricky situations. You can trigger the long-press Power menu on your Android phone or tablet using ADB Shell commands.

    Just launch the command window, connect your phone to the computer and execute the following command:

    This will make the Android Power menu appear and you can then select the Power Off or Reboot option as per your choice.

    Power Off Android via Accessibility Menu

    All Android devices have a set of Accessibility settings to help physically and visually impaired people. Among the key features of Android’s Accessibility are Talkback and Accessibility or Assistant Menu. By enabling this menu, you can add an Accessibility shortcut in the navigation bar of your Android phone or tablet or get a floating menu icon. You can enjoy quick shortcuts to launch Google Assistant, Recents, Power Menu, Screenshots, and so on simply by tapping the Accessibility Menu icon.

    Let’s see how we can turn off an Android phone or tablet without the Power button via Accessibility Menu.

    Читайте также:  Creating intent in android

    1. Open Settings on your Android device and tap on Accessibility. On the devices from Chinese OEMs like Xiaomi, Vivo, Oppo, OnePlus, Realme, Huawei, etc., you’ll find Accessibility under Additional settings.
    2. If you own a Samsung Galaxy phone or Tab, select Interaction and dexterity and tap on the toggle icon in front of the Assistant menu. A floating icon for the Assistant menu will appear on the screen as shown below. If you find that floating icon irritating, you can change its size, appearance location, etc. by tapping on the Assistant menu option.
    3. Just tap on the floating Assistant menu icon to access the Power off menu. You can now turn off your Samsung Galaxy device without using the Power button.
    4. If you have a phone from Xiaomi, Redmi, Vivo, Oppo, OnePlus, Realme, or Huawei, you are supposed to enable the Accessibility menu from Accessibility. As soon as you enable it, the Accessibility menu icon will appear on the navigation bar. Just tap it to access the option to Power off your phone without using the Power button.

    Turn off Android Phone Using Apps

    The Google Play Store is overloaded with apps for everything. You can find hundreds of apps that can let your power off and reboot a phone with a broken Power button. All such apps require either Accessibility permission or root privilege and offer similar options like the Accessibility menu shown above.

    I tested some of the most rated and popular apps that offer the option to turn off and reboot Android devices without pressing the Power key. Below, I am going to list the ones that are worth a try.

    Phone Lock + Volume Control (OFF+)

    Phone Lock + is a minimal app with no regular user interface as most apps have. Nonetheless, the app does its job and doesn’t require root.

    When Phone Lock is installed on your device, launch it from the app drawer. It’ll prompt you to select one of the 2 lock modes. Make your choice and grant Accessibility permission to the app when asked to do so. Now, whenever you want to access the Power Menu to switch off or restart your phone, just tap and hold the Phone Lock app icon. Please note that just taping the app icon will lock your device either immediately or after 5 seconds.

    Power Menu: Software Power Button

    Power Menu is another simple app that lets you launch the Power Menu with a single tap without holding the Power button. Of course, it will ask you to grant Accessibility permission under Installed Services for the first time.

    Assistive Touch for Android

    If you prefer to have a persistent floating button to access the Power Menu and lots of other things quickly without using the Power button, volume buttons, and the navigation bar keys, Assistive Touch for Android is a great option for you.

    Just tap on the floating touch icon and tap on the Power menu icon to turn off your Android phone or tablet if the Power button is broken or not working. One thing that I hate about this app is that it has too many irritating ads.

    Turn off Phone via Quick Settings (Samsung)

    Well, older Samsung devices didn’t have it, but if you have a Samsung Galaxy phone or Tab released in 2019 or later, you must have seen the Power Menu icon located in the Quick Settings screen. Phones like Galaxy Note 10, Note 20, Galaxy S10, S20, Galaxy A70, Galaxy A51, etc., have this shortcut.

    You can tap on the Power Menu icon to select the option to reboot or turn off your Samsung Galaxy device without the Power button.

    Turn off Samsung Device via Bixby

    Samsung Galaxy users can also turn off their phone without using the Power key using a Bixby voice command. I tried this using Google Assistant commands a well but it did not work.

    Launch Samsung Bixby and use “Turn off/Power off the phone” command. Bixby will ask you to select the Power off option. Just tap on it to shut down your Samsung device.

    Schedule Power Off Time via Android Settings

    Another way to turn off an Android phone without the Power button is by scheduling the power-off time via your device settings.

    1. Open Settings on your device.
    2. Tap the Search icon or bar on the settings menu page and type “schedule” in it.
    3. You’ll get a list of items that can be scheduled. Tap on Schedule power on/off.
    4. On the next page, you can set the time when you want to power on or off your Android device automatically without using the Power key.

    That’s all for now about turning off an Android device when the Power button is broken, the screen is black and the touch is not working. I hope the tips given here will also let you restart the phone without the power button. If you think I have missed any working method, please let me know.

    Источник

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