Android disable screen timeout while app is running

Solution 1:

You want to use something like this:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Solution 2:

I used:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

to disable the screen timeout and

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

to re-enable it.

Solution 3:

There is also a XML way that Google recommends:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:keepScreenOn="true">

Check Google Slides - Slide 16.

"Wakelocks are costly if forgotten (...) Consider using android:keepScreenOn to ensure correctness"

Solution 4:

In a View, in my case a SurfaceView subclass, you can set the screen on always on. I wanted the screen to stay on while this view was still drawing stuff.

public class MyCoolSurfaceView extends SurfaceView { 
@Override
protected void onAttachedToWindow (){
    super.onAttachedToWindow();
    this.setKeepScreenOn(true);
}

@Override
protected void onDetachedFromWindow(){
    super.onDetachedFromWindow();
    this.setKeepScreenOn(false);
}

Solution 5:

Its importante to note that these methods all must be run from the UI thread to work. See changing KeepScreenOn from javascript in Android cordova app