Keep the screen on v4.1.x


I have the following code to keep the screen always on:

if (usuario.getTelaLigada()){   

It works in version 4.4 and higher. But not in previous ones.

How do I keep the screen switched on in all versions?

Thank you!

asked by anonymous 17.12.2015 / 10:37

1 answer


A very common practice in Android development is to use PowerManager.WakeLock to do such a task. However, this is not the ideal and most reliable option, since you will need to add more permission on your application just for that.

In addition, if you accidentally (or some other developer on your team) forget to turn it off, you can drain the battery from your user's device.

For this, I recommend that you use the setKeepScreenOn() method inside the View class:

If you are creating some view via code:

protected void onCreate(Bundle savedInstanceState) {

    View view = getLayoutInflater().inflate(R.layout.driver_home, null);

Or, via xml:




NOTE: It does not matter if the keepScreenOn flag is in your main layout, root, or other layout within your views tree, it will work the same way on any component in your xml . The only point is that the visibility of this view must be visible , otherwise it will not work!

18.12.2015 / 02:20