Keep screen on v4.1.x

Asked

Viewed 416 times

3

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

if (usuario.getTelaLigada()){   
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

Works in version 4.4 and higher. But not the previous ones.

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

Thank you!

  • 2

    Check this out: http://stackoverflow.com/questions/24031838/turning-screen-on-off-android

1 answer

3


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, as you will need to add an extra permission in your application just for this.

Also, if you accidentally (or some other developer of your team) forget to turn it off, you may drain the battery from your user’s device.

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

If you are creating some view via code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    View view = getLayoutInflater().inflate(R.layout.driver_home, null);
    view.setKeepScreenOn(true);
    setContentView(v);
}

Or, via xml:

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">

    ...

</RelativeLayout>

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.