If you need to keep a device running in order to complete some work before the
device goes into the suspend state, you can use a PowerManager
system
service feature called wake locks. Wake locks allow your app to control the
power state of the device.
Set a wake lock
To use a wake lock, the first step is to add the
WAKE_LOCK
permission to
your application's manifest file:
<uses-permission android:name="android.permission.WAKE_LOCK" />
If your app includes a broadcast receiver that uses a service to do some work, here is how you set a wake lock directly:
Kotlin
val wakeLock: PowerManager.WakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).run { newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp::MyWakelockTag").apply { acquire() } }
Java
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp::MyWakelockTag"); wakeLock.acquire();
Release a wake lock
To release the wake lock, call wakelock.release()
. Doing so releases your
claim to the CPU. It's important to release a wake lock as soon as your app is
finished using it to avoid draining the battery.