How do I prevent an Android device from going to sleep programmatically?
Asked Answered
F

9

172

How do I prevent an Android device from going to sleep programmatically?

Flameproof answered 16/9, 2010 at 4:6 Comment(0)
T
138

One option is to use a wake lock. Example from the docs:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();

// screen and CPU will stay awake during this section

wl.release();

There's also a table on this page that describes the different kinds of wakelocks.

Be aware that some caution needs to be taken when using wake locks. Ensure that you always release() the lock when you're done with it (or not in the foreground). Otherwise your app can potentially cause some serious battery drain and CPU usage.

The documentation also contains a useful page that describes different approaches to keeping a device awake, and when you might choose to use one. If "prevent device from going to sleep" only refers to the screen (and not keeping the CPU active) then a wake lock is probably more than you need.

You also need to be sure you have the WAKE_LOCK permission set in your manifest in order to use this method.

Tosh answered 16/9, 2010 at 4:11 Comment(5)
You should not use this anymore since this method is deprecated now. Take a look at one of the other answers.Emmanuelemmeline
There are still some reasons to use wakelocks, like if the device is dedicated to a specific app and needs to run even when minimized.Sammysamoan
PowerManager.PARTIAL_WAKE_LOCK is not deprecated and I think it’s the most efficient method. It allows the user to press the power button but the CPU will still turned on until the user call release();Enabling
Official Documentation says "If you need to keep the CPU running in order to complete some work before the device goes to sleep, you can use a PowerManager system service feature called wake locks."Ferruginous
This is great way, but it is deprecated. please check this answer : https://mcmap.net/q/144787/-what-should-i-replace-screen_dim_wake_lock-withTambourine
P
271

If you just want to prevent the sleep mode on a specific View, just call setKeepScreenOn(true) on that View or set the keepScreenOn property to true. This will prevent the screen from going off while the View is on the screen. No special permission required for this.

Promiscuous answered 1/7, 2011 at 22:28 Comment(6)
Also this will not force the phone to stay awake outside the life span of the application. You can run into that problem with WakeLock.Ostracism
Yes, in most cases, this is the better approach.Tridactyl
This should be the selected answer. Simple, clean and as Android intended. Thank you.Lainelainey
"Using android:keepScreenOn="true" is equivalent to using FLAG_KEEP_SCREEN_ON. You can use whichever approach is best for your app. The advantage of setting the flag programmatically in your activity is that it gives you the option of programmatically clearing the flag later and thereby allowing the screen to turn off" - developer.android.com/training/scheduling/wakelock.htmlCookgeneral
Note that the setKeepScreenOn(true) will take effect only when View is visible.Nicholenicholl
what if my app has video recording which works in background (service)? there is no activity in foreground, so no, xml keep screen on is not an answer..Ledge
T
138

One option is to use a wake lock. Example from the docs:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();

// screen and CPU will stay awake during this section

wl.release();

There's also a table on this page that describes the different kinds of wakelocks.

Be aware that some caution needs to be taken when using wake locks. Ensure that you always release() the lock when you're done with it (or not in the foreground). Otherwise your app can potentially cause some serious battery drain and CPU usage.

The documentation also contains a useful page that describes different approaches to keeping a device awake, and when you might choose to use one. If "prevent device from going to sleep" only refers to the screen (and not keeping the CPU active) then a wake lock is probably more than you need.

You also need to be sure you have the WAKE_LOCK permission set in your manifest in order to use this method.

Tosh answered 16/9, 2010 at 4:11 Comment(5)
You should not use this anymore since this method is deprecated now. Take a look at one of the other answers.Emmanuelemmeline
There are still some reasons to use wakelocks, like if the device is dedicated to a specific app and needs to run even when minimized.Sammysamoan
PowerManager.PARTIAL_WAKE_LOCK is not deprecated and I think it’s the most efficient method. It allows the user to press the power button but the CPU will still turned on until the user call release();Enabling
Official Documentation says "If you need to keep the CPU running in order to complete some work before the device goes to sleep, you can use a PowerManager system service feature called wake locks."Ferruginous
This is great way, but it is deprecated. please check this answer : https://mcmap.net/q/144787/-what-should-i-replace-screen_dim_wake_lock-withTambourine
N
133

I found another working solution: add the following line to your app under the onCreate event.

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

My sample Cordova project looks like this:

package com.apps.demo;
import android.os.Bundle;
import android.view.WindowManager;
import org.apache.cordova.*;

public class ScanManActivity extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.loadUrl("http://stackoverflow.com");
    }
}

After that, my app would not go to sleep while it was open. Thanks for the anwer goes to xSus.

Nostology answered 1/8, 2012 at 21:36 Comment(6)
this was the best option in my opinion... +1Glyptography
This does the same as the Witek answer, the only difference is that you put this in a ".java" file instead of a ".xml" one ;-)Anthropophagite
How about permission? Is it require permission?Planoconvex
@Mehdi Khademloo it doesn't need permission.Korte
what if my app has video recording which works in background (service)? there is no activity in foreground, so no, xml keep screen on is not an answer..Ledge
owh... let me use this on API Level 30.Anabas
R
38

android:keepScreenOn="true" could be better option to have from layout XML.

More info: https://developer.android.com/training/scheduling/wakelock.html

Renfred answered 24/9, 2014 at 6:59 Comment(2)
what if my app has video recording which works in background (service)?Ledge
that's intersting usecase :) ..need to do some google resarch if ever possible.Renfred
C
27

Set flags on Activity's Window as below

@Override public void onResume() {
 super.onResume();
 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

@Override public void onPause() {
 super.onPause();
 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
Columbous answered 9/2, 2017 at 17:58 Comment(0)
B
7

From the root shell (e.g. adb shell), you can lock with:

echo mylockname >/sys/power/wake_lock    

After which the device will stay awake, until you do:

echo mylockname >/sys/power/wake_unlock    

With the same string for 'mylockname'.

Note that this will not prevent the screen from going black, but it will prevent the CPU from sleeping.

Note that /sys/power/wake_lock is read-write for user radio (1001) and group system (1000), and, of course, root.

A reference is here: http://lwn.net/Articles/479841/

Brahmanism answered 23/9, 2013 at 20:58 Comment(0)
C
3

what @eldarerathis said is correct in all aspects, the wake lock is the right way of keeping the device from going to sleep.

I don't know waht you app needs to do but it is really important that you think on how architect your app so that you don't force the phone to stay awake for more that you need, or the battery life will suffer enormously.

I would point you to this really good example on how to use AlarmManager to fire events and wake up the phone and (your app) to perform what you need to do and then go to sleep again: Alarm Manager (source: commonsware.com)

Cressy answered 16/9, 2010 at 10:45 Comment(1)
There are utility apps specifically and purposefully meant to drain the battery. I had a need for one one time. Basically it would acquire wakelocks, vibrate like crazy, turn on flashlight, increase the brightness, etc. So yes, there are apps that make use of this. But this was off topic so forgive meCollen
D
2

Simply use the Kotlin way:

window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

Example:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}

Source: Keep the screen on

Dimitri answered 3/4, 2023 at 9:44 Comment(0)
I
1

If you are a Xamarin user, this is the solution:

   protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle); //always call superclass first

        this.Window.AddFlags(WindowManagerFlags.KeepScreenOn);

        LoadApplication(new App());
    }
Insincerity answered 24/6, 2019 at 17:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.