- 3 Ways to Stop Android Phone Screen From Turning Off Automatically
- Stop Phone Screen from Turning off Completely
- 1. Via Display Settings
- 2. Via Developer Options
- 3. Via Third-party Apps
- Wrapping up
- Android: как включить и выключить экран программно?
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Ответ 11
- Ответ 12
- Ответ 13
- Ответ 14
- Ответ 15
- Ответ 16
- Android: How to turn screen on and off programmatically?
- Related Posts
- android – How do I display a CalendarView in an AlertDialog?
- How do I convert a PSD design to Android xml?
3 Ways to Stop Android Phone Screen From Turning Off Automatically
How many times it happened to you when you try to read something on your phone and the screen goes off? Screen timeout is the setting on your phone which automatically turns off the display in order to save the battery. Since Android phones are completely customizable this setting also has some options to choose from, and on some phones, you can even completely turn it off. So, here I am telling you the ways to stop the phone screen from turning off. Read on!
Stop Phone Screen from Turning off Completely
Table of Contents
If you want to completely turn off this setting then there is an option in the display setting. If you don’t find the option to turn it off, don’t worry we have another trick up our sleeve to tell you about.
1. Via Display Settings
1. Pull down the notification panel and tap the little setting icon to go to Settings.
2. In the Settings menu, go to the Display and look for the Screen Timeout settings.
3. Tap the Screen Timeout setting and select the duration you want to set or just select “Never” from the options.
If you won’t see the Never option in the settings but you still want to keep your device awake for longer then follow the next method.
2. Via Developer Options
1. Go to Settings > About Phone > tap on Build Number 7 times.
2. Navigate back to Settings > System > Developer Options.
3. Look for Stay Awake option and enable it.
Now while your phone is on charging, the screen will not turn off automatically unless you remove the charger. In that case, the default setting will enable which you selected in the display setting.
3. Via Third-party Apps
You can also prevent your phone screen from turning off completely using a third-party app. There are plenty of such apps available on the Play Store, and we are using “Caffeine”. Here’s how to use it:
1. Download and install Caffeine – Keep Screen On from the Play Store.
2. The app works via a toggle, so you will need to add this to the Quick Settings panel.
3. Pull down the Quick Settings panel and tap on the Pencil icon to edit it.
4. Now look for the Coffee Mug icon among all quick settings.
5. Move this “Caffeine” toggle to the Quick Settings panel by holding and dragging it.
7. When the toggle is in the main Quick Settings panel, you can use it anytime.
Whenever you want to change the screen timeout time, swipe down to open the Quick Settings, and tap the Coffee Mug icon. By default, it sets screen timeout to Infinite, but it also has a number of other customization options.
Wrapping up
This is how you can make your smartphone screen never go off while you are reading something important on it. Tell us in the comments, which of the above-mentioned ways will you use to increase screen timeout on your phone.
For more Android tips and tricks, stay tuned.
You can also follow us for instant tech news at Google News or for tips and tricks, smartphones & gadgets reviews, join GadgetsToUse Telegram Group or for the latest review videos subscribe GadgetsToUse Youtube Channel.
Источник
Android: как включить и выключить экран программно?
Прежде чем отмечать этот пост как «дубликат», я пишу этот пост, потому что никакая другая почта не имеет решения проблемы.
Я пытаюсь выключить устройство, а затем через несколько минут или сменить датчик, снова включите его.
Отключить показания дисплея
Я могу отключить экран, используя:
Мне не удалось отключить экран, используя метод wl.release().
Включить проверку дисплея
Мое первое предположение, как показано ниже, не работает. Ничего не происходит, экран остается выключенным.
Я также попытался использовать wakelocks, без успеха.
Наконец, я пробовал следующее, без результата.
В целом, я не получаю никаких ошибок в консоли для любого из этих методов. Мой тестовый текст «Экран должен быть включен», находится на экране, когда я включаю устройство с помощью кнопки питания. Это показывает, что код должен работать. Пожалуйста, ответьте только, если вы протестировали код, кажется, что многие из функций, таких как params.screenBrightness = -1 , не работают так, как должны, согласно sdk.
ОТВЕТЫ
Ответ 1
Я собираюсь предположить, что вы хотите, чтобы это действовало, пока ваше приложение находится на переднем плане.
Не выключает экран в традиционном смысле. Это делает экран настолько тусклым, насколько это возможно. В стандартной платформе существует предел того, насколько он может быть тусклым; если ваше устройство действительно позволяет экрану полностью отключиться, то это определенная особенность реализации этого устройства, а не поведение, которое вы можете рассчитывать на разных устройствах.
Фактически использование этого в сочетании с FLAG_KEEP_SCREEN_ON означает, что вы никогда не позволяете экрану отключиться (и, следовательно, устройство переходит в режим с низким энергопотреблением), даже если конкретное устройство позволяет вам установить яркость экрана на полный -off. Имейте это в виду. Вы будете использовать гораздо больше энергии, чем если бы экран был действительно выключен.
Теперь, чтобы вернуть экран к обычной яркости, просто установите значение яркости:
Я не могу объяснить, почему это не заменит ранее установленное значение 0. В качестве теста вы можете попытаться установить принудительную полную яркость, чтобы заставить эту конкретную яркость:
Это определенно работает. Например, приложения Google Книги используют это, чтобы вы могли установить яркость экрана при использовании книги, а затем при обычной выдержке вернуться к обычной яркости.
Чтобы отладить, вы можете использовать «окно dumpsys оболочки adb», чтобы увидеть текущее состояние вашего окна. В данных для вашего окна он скажет вам текущие LayoutParams, которые были установлены для него. Убедитесь, что вы действительно на самом деле находитесь.
И снова FLAG_KEEP_SCREEN_ON — это отдельная концепция; он и яркость не оказывают прямого воздействия друг на друга. (И не было бы причин снова устанавливать флаг при отмене яркости, если вы уже установили его при установке яркости на 0. Флаг останется установленным до тех пор, пока вы его не измените.)
Ответ 2
Я написал этот метод, чтобы включить экран после блокировки экрана. Он отлично работает для меня. Попробуйте it-
И назовите этот метод из onResume() .
Ответ 3
Я бы предложил следующее:
Флаг ACQUIRE_CAUSES_WAKEUP объясняется следующим образом:
Обычные блокировки от бодрствования фактически не включают подсветку. Вместо, они заставляют освещение оставаться включенным после его включения (например, из активность пользователя). Этот флаг заставит экран и/или клавиатуру немедленно включается, когда приобретается WakeLock. Типичное использование будет для уведомлений, которые важны для пользователя, чтобы видеть немедленно.
Кроме того, убедитесь, что у вас есть следующее разрешение в файле AndroidManifewst.xml:
Ответ 4
Привет, надеюсь, это поможет:
Ответ 5
//Файл манифеста пользователя
Ответ 6
Вы уверены, что запросили правильное разрешение в вашем файле манифеста?
Вы можете использовать класс AlarmManager 1, чтобы сбить намерение, которое начинает вашу деятельность, и получает блокировку слежения. Это включит экран и сохранит его. Освобождение wakelock позволит устройству самостоятельно спать.
Вы также можете взглянуть на использование PowerManager, чтобы установить устройство в режим сна: http://developer.android.com/reference/android/os/PowerManager.html#goToSleep(long)
Ответ 7
Вот успешный пример реализации того же самого, на устройстве, которое поддерживает более низкие значения яркости экрана (я тестировал на планшете Allwinner Chinese 7 «с API15).
Если кто-то еще это попробует, комментарий PLS ниже, если он работал/не работал и устройство Android API.
Ответ 8
Лучший способ сделать это (с использованием корневых устройств):
Теперь у нас есть две функции:
Извините за мой плохой английский.
Ответ 9
Это работает над Marshmallow
Ответ 10
Чтобы включить экран:
Возврат к режиму по умолчанию: просто очистите флаг FLAG_KEEP_SCREEN_ON
Ответ 11
Если ваше приложение является системным приложением, вы можете использовать PowerManager.goToSleep() для выключения экрана, вам требуется специальное разрешение
перед использованием goToSleep() вам нужно использовать отражение так же, как:
Теперь вы можете использовать goToSleep(), чтобы выключить экран.
Это то, что происходит при нажатии клавиши питания для выключения экрана.
Ответ 12
У меня не было бы надежды на «пробуждение экрана» в действии. Если экран выключен, действие, вероятно, находится в состоянии паузы и не должно содержать никакого кода.
При просыпании возникает проблема блокировки экрана. Я не знаю, как любое приложение может автоматически обойти lockscreen.
Вам следует рассмотреть возможность запуска фоновых задач в службе, а затем с помощью диспетчера уведомлений отправить уведомление, когда все обнаружено. Уведомление должно предоставлять какое-либо предупреждение устройства (пробуждение экрана, значок уведомления, уведомление и т.д.). При нажатии на уведомление он может запустить намерение начать свою деятельность.
Вы также можете попытаться запустить действие непосредственно из службы, но я действительно не знаю, включит ли это экран или обойдется экран блокировки.
Ответ 13
Что касается документации Android, ее можно достичь, используя следующую строку кода:
Я добавил это в мой метод onCreate , и он отлично работает.
В ссылке вы найдете разные способы достижения этого и общее объяснение.
Ответ 14
или позвоните по телефону
на родительском представлении.
Ответ 15
В соответствии с Android API 28 и выше вам нужно сделать следующее, чтобы включить экран
Ответ 16
Бывают случаи, когда экран необходимо отключить ПОЛНОСТЬЮ. Если энергопотребление не очень важно для вашего приложения, класс PowerManager может использоваться в следующих случаях:
- Используйте PowerManager.goToSleep(), чтобы отключить отображение экрана.
- Используйте PowerManager.wakeUp(), чтобы включить экран.
- Используйте PowerManager.isScreenOn(), чтобы получить состояние включения/выключения экрана. Кроме того, для этой цели используйте PowerManager.isInteractive() или Display.getState().
В следующем примере кода показано, как реализовать это решение:
Данный код был протестирован на встроенном устройстве под управлением Android 4.4.2 (API уровня 19).
Обратите внимание, что некоторые из этих методов API не могут быть найдены в документации API Android, и вам необходимо указать соответствующие разрешения, такие как DEVICE_POWER.
Источник
Android: How to turn screen on and off programmatically?
Posted by: admin December 4, 2017 Leave a comment
Before marking this post as a “duplicate”, I am writing this post because no other post holds the solution to the problem.
I am trying to turn off the device, then after a few minutes or sensor change, turn it back on.
Turn Off Display Tests
I am able to turn off the screen using:
I have been unable to turn off the screen using the wl.release() method.
Turn On Display Test
My first guess, as follows, does not work. Nothing happens, screen remains off.
I also then tried to use wakelocks, with no success.
Finally I have tried the following, with no result.
All in all, I don’t get any kind of error in the console for any of these methods. My test text “Screen should be on”, is on the the screen when I turn on the device using the power button. This shows that the code should have ran. Please only answer if you have tested the code, it seems like many of the functions such as params.screenBrightness = -1 , do not work as they should according to the sdk.
I am going to assume you only want this to be in effect while your application is in the foreground.
Does not turn the screen off in the traditional sense. It makes the screen as dim as possible. In the standard platform there is a limit to how dim it can be; if your device is actually allowing the screen to turn completely off, then it is some peculiarity of the implementation of that device and not a behavior you can count on across devices.
In fact using this in conjunction with FLAG_KEEP_SCREEN_ON means that you will never allow the screen to go off (and thus the device to go into low-power mode) even if the particular device is allowing you to set the screen brightness to full-off. Keep this very strongly in mind. You will be using much more power than you would if the screen was really off.
Now for turning the screen back to regular brightness, just setting the brightness value should do it:
I can’t explain why this wouldn’t replace the 0 value you had previously set. As a test, you could try putting a forced full brightness in there to force to that specific brightness:
This definitely works. For example, Google’s Books apps uses this to allow you to set the screen brightness to dim while using a book and then return to regular brightness when turning that off.
To help debug, you can use “adb shell dumpsys window” to see the current state of your window. In the data for your window, it will tell you the current LayoutParams that have been set for it. Ensure the value you think is actually there.
And again, FLAG_KEEP_SCREEN_ON is a separate concept; it and the brightness have no direct impact on each other. (And there would be no reason to set the flag again when undoing the brightness, if you had already set it when putting the brightness to 0. The flag will stay set until you change it.)
I had written this method to turn on the screen after screen lock. It works perfectly for me. Try it-
And call this method from onResume() .
I would suggest this one:
The flag ACQUIRE_CAUSES_WAKEUP is explained like that:
Normal wake locks don’t actually turn on the illumination. Instead,
they cause the illumination to remain on once it turns on (e.g. from
user activity). This flag will force the screen and/or keyboard to
turn on immediately, when the WakeLock is acquired. A typical use
would be for notifications which are important for the user to see
immediately.
Also, make sure you have the following permission in the AndroidManifewst.xml file:
Hi I hope this will help:
Are you sure you requested the proper permission in your Manifest file?
You can use the AlarmManager1 class to fire off an intent that starts your activity and acquires the wake lock. This will turn on the screen and keep it on. Releasing the wakelock will allow the device to go to sleep on its own.
You can also take a look at using the PowerManager to set the device to sleep: http://developer.android.com/reference/android/os/PowerManager.html#goToSleep(long)
//User Manifest file
Here is a successful example of an implementation of the same thing, on a device which supported lower screen brightness values (I tested on an Allwinner Chinese 7″ tablet running API15).
If someone else tries this out, pls comment below if it worked/didn’t work and the device, Android API.
The best way to do it ( using rooted devices) :
Now we have this two functions:
Sorry for my bad english.
I wouldn’t have hope of “waking the screen” in the activity. If the screen is off the activity is probably in a paused state and shouldn’t be running any code.
When waking up, there is the issue of the lockscreen. I don’t know how any app can automatically bypass the lockscreen.
You should consider running your background tasks in a service, and then using the notification manager to send a notification when whatever is detected. The notification should provide some sort of device alert (screen wake up, notification icon, notification led, etc). When clicking the notification it can launch the intent to start your activity.
You could also attempt to start the activity direct from the service, but I really don’t know if that will turn the screen on or bypass the lockscreen.
Regarding to Android documentation it can be achieve by using following code line:
I have added this in my onCreate method and it works fine.
On the link you will find different ways to achieve this and general explanation as well.
To keep screen on:
Back to screen default mode:
just clear the flag FLAG_KEEP_SCREEN_ON
There are cases where the screen needs to be turned off COMPLETELY. If power saving is not a big concern for your app, the PowerManager class can be used in these cases:
- Use PowerManager.goToSleep() to turn off the screen display.
- Use PowerManager.wakeUp() to turn on the screen display.
- Use PowerManager.isScreenOn() to get the on/off state of the screen display. Alternatively, use PowerManager.isInteractive() or Display.getState() for this purpose.
The following code example shows how to implement this solution:
The above code has been tested on an embedded device running Android 4.4.2 (API level 19).
Note that some of these API methods may not be found in Android API documentation, and you need to specify appropriate permissions such as DEVICE_POWER.
Related Posts
android – How do I display a CalendarView in an AlertDialog?
Questions: I’m trying to display the CalendarView in an Alert Dialog, but all that shows up is the month/year and the days of the week. These are the contents of the layout file:
How do I convert a PSD design to Android xml?
Questions: Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. Want to improve this question? Update the question so it’s on-topic for Stack Over.
Источник