Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android disable screen timeout while app is running

Tags:

android

People also ask

How do you make phone not Sleep on certain apps?

Download the Keep Screen On app from the Google Play Store. Grant the app Usage Access by following the on-screen instructions. You'll see a list of the Downloaded apps installed on your device, so simply tap on the one you want to keep the screen on for.

How do I get rid of screen timeout on Android?

All you need to do is click on the settings menu from the notification panel or the app drawer and go to the settings icon. Now click on the Display icon. Click on Screen Timeout and click on the Never option. After Clicking on Screen timeout your phone screen will stop turning off.


You want to use something like this:

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

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.


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"


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);
}

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


Simple add below line into your MainActivity and your App never turn lights off.

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

Put this at onStart

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "no sleep");
    wakeLock.acquire();

And this at you manifest

    <uses-permission android:name="android.permission.WAKE_LOCK" />

Don't forget to

wakeLock.release();

at onStop