- Handling Screen OFF and Screen ON Intents
- 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: Как программно включать и выключать экран?
- 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?
Handling Screen OFF and Screen ON Intents
Haven’t posted in a while – sorry school has been busy. Any who, this little code snippet/example will be on how to deal with the Intent.ACTION_SCREEN_OFF and the Intent.ACTION_SCREEN_ON, which will come in nifty if you’re making an application that might need to save state or respond to the user’s screen going to sleep/waking up, etc.
First, unlike other broad casted intents, for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON you CANNOT declare them in your Android Manifest! I’m not sure exactly why, but they must be registered in an IntentFilter in your JAVA code. And so, for this example we are going to have a receiver called ScreenReceiver, and I’m going to walk you through the differences between implementing it in a Service vs. in an Activity.
So, the receiver will simply look like:
Now, the first example will be for an Activity. Because of the life-cycle of an Activity, an Activity is actually easier to deal with as right before the screen turns off onPause() is called and right when the screen turns on onResume() is called, and so naturally we will handle the screen on/off events here:
Now, note that in my onPause() and onResume() methods I run a check to see that the method was called DUE TO A SCREEN STATE CHANGE. This is important as often onPause() or onResume() will get called because of other reasons – i.e. a new activity is being started on top of this one, or an incoming call might be coming in, etc – and you want to make sure that your screen change logic is only called when the screen has actually changed.
Now, something to keep in mind, is that the order of events before the system screen turns off is:
Which is a little unintuitive as you’d think the receiver would get hit first – and so when you play around with setting booleans, etc, be aware of this little fact, and likewise when the screen turns on the order of events is:
And so again the order of events seems a little “backwards”.
Now, for a Service, it’s a little bit different since there is no onResume() or onPause() that gets called as the Service is always “running” in the background, and so instead what you’re going to have to do is modify your receiver a little to look like:
And your service will look like:
And so this is pretty self explanatory. When the screen state changes, it will notify your ScreenReceiver and from there you can set the state information into an Intent and send that data to your Service which can then handle it appropriately.
Hopefully this was useful. Let me know if you have questions.
Источник
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.
Я предполагаю, что вы хотите, чтобы это действовало только тогда, когда ваше приложение находится на переднем плане.
Не выключает экран в традиционном понимании. Это делает экран максимально тусклым. В стандартной платформе есть ограничение на то, насколько тусклым он может быть; Если ваше устройство действительно позволяет экрану полностью отключиться, то это некоторая особенность реализации этого устройства, а не поведение, на которое вы можете рассчитывать на разных устройствах.
Фактически, использование этого в сочетании с FLAG_KEEP_SCREEN_ON означает, что вы никогда не позволите экрану выключиться (и, следовательно, устройству перейти в режим низкого энергопотребления), даже если конкретное устройство позволяет вам установить яркость экрана на полную. Имейте это в виду. Вы будете использовать гораздо больше энергии, чем если бы экран был действительно выключен.
Теперь, чтобы вернуть экран к нормальной яркости, достаточно установить значение яркости:
Я не могу объяснить, почему это не заменит ранее установленное вами значение 0. В качестве теста вы можете попробовать установить принудительную полную яркость, чтобы добиться этой конкретной яркости:
Это определенно работает. Например, приложения Google Книги используют это, чтобы вы могли настроить яркость экрана на затемнение при использовании книги, а затем вернуться к обычной яркости при выключении.
Чтобы облегчить отладку, вы можете использовать «adb shell dumpsys window», чтобы увидеть текущее состояние вашего окна. В данных для вашего окна он сообщит вам текущие LayoutParams, которые были установлены для него. Убедитесь, что ценность, которую вы думаете, действительно существует.
И снова FLAG_KEEP_SCREEN_ON — это отдельная концепция; он и яркость не влияют друг на друга напрямую. (И не было бы причин снова устанавливать флаг при отмене яркости, если вы уже установили его при установке яркости на 0. Флаг останется установленным, пока вы его не измените.)
Источник
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.
Источник