How to Keep the Device Screen On in Android?
In Android it’s seen that screen timeout will be set for 30 seconds or it is set by the user manually in system settings, to avoid the battery drain. But there are cases where applications like stopwatch, document reader applications, games, etc, need the screen to be always awake. In this article its been demonstrated, how to keep the device screen awake.
Steps for Keeping the Device Screen On
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Change the color combination of the base theme of the application
- To change the base application theme colors Goto app -> res -> values -> colors.xml, and invoke the following color combination.
- Refer the following image if one has not got the colors.xml file:
Step 3: Working with the activity_main.xml file
In the activity_main.xml file add TextViews to make an app like the document reading application.
The following output UI is produced:
Step 4: Working on keep the device screen awake
There are two methods to implement the screen always awake.
Method 1: Invoking the “keepScreenOn” as true
One can keep the device screen awake by invoking the following attribute in the root view of the application.
android:keepScreenOn = “true”
You can have a look at the following activity_main.xml code:
Method 2: Keep screen on programmatically
Now you can remove the attribute android:keepScreenOn=”true” from the activity_main.xml file and rest all code remains the same and invoke the following code in MainActivity.java file.
The complete code is given below.
The output is produced as the following image (it is recommended to test this application in a physical android device so that you can see the result whether the app screen is awake or not) and both method’s output will remain the same:
Which method is recommended?
Both the methods are the same and one can use whichever it feels better, but implementing this programmatically is recommended because in complex android applications, developers set the many flags in a particular activity and it becomes easy to get those all flags and manually disable and manage them.