Set a wake lock

You can set a wake lock to temporarily keep the device awake.

Dependencies

Your app must have the WAKE_LOCK permission to set a wake lock. Add the permission to your app's manifest:

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

Create and acquire a wake lock

To acquire a wake lock, do the following:

  1. Call PowerManager.newWakeLock() to create a wake lock. This creates and configures a PowerManager.WakeLock object but does not actually keep the device awake.

  2. When you want to keep the device awake, call the wake lock object's acquire() method.

For example, if your app includes a broadcast receiver that uses a service to do some work, you can use this code to set and acquire a wake lock:

Kotlin

val wakeLock: PowerManager.WakeLock =
    (getSystemService(Context.POWER_SERVICE) as PowerManager).run {
        newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyClassName::MyWakelockTag").apply {
            acquire()
        }
    }

Java

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        "MyClassName::MyWakelockTag");
wakeLock.acquire();

Key points about this code

When the code creates the wake lock object, it uses the class's name as part of the wake lock tag. We recommend including your package, class, or method name as part of the wake lock tag. That way, if an error occurs, it's easier to locate the wake lock in your source code. For more information, see Name the wake lock properly.

See also