释放唤醒锁定
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
本页介绍了如何释放应用持有的唤醒锁定。请务必在应用结束对唤醒锁定的使用后立即将其释放,以避免消耗电池电量。
释放有效的唤醒锁定
如需释放有效的唤醒锁定,请调用其 release()
方法。这样做会释放您对 CPU 的声明。
例如,以下代码获取唤醒锁定,执行一些工作,然后释放唤醒锁定:
Kotlin
@Throws(MyException::class)
fun doSomethingAndRelease() {
wakeLock.apply {
try {
acquire()
doTheWork()
} finally {
release()
}
}
}
Java
void doSomethingAndRelease() throws MyException {
try {
wakeLock.acquire();
doTheWork();
} finally {
wakeLock.release();
}
}
确保在不再需要唤醒锁定时立即释放。例如,如果您使用唤醒锁定来促使后台任务完成,请确保在任务完成后立即释放锁定。
此代码的相关要点
在此示例中,方法 doTheWork()
可能会抛出异常。因此,代码会在 finally
块中释放唤醒锁定,以确保无论是否抛出异常,唤醒锁定都会被释放。请务必确保释放您设置的每个唤醒锁定,因此您需要检查每个可能的代码路径,以确保唤醒锁定不会在任何路径上保持有效状态。
另请参阅
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-24。
[null,null,["最后更新时间 (UTC):2025-08-24。"],[],[],null,["# Release a wake lock\n\nThis page describes how to release a wake lock held by your app.\nIt's important to release a wake lock as soon as your app is\nfinished using it to avoid draining the battery.\n\nRelease an active wake lock\n---------------------------\n\nTo release an active wake lock, call its [`release()`](/reference/android/os/PowerManager.WakeLock#release()) method. Doing so\nreleases your claim to the CPU.\n\nFor example, the following code [acquires a wake lock](/develop/background-work/background-tasks/awake/wakelock/set),\ndoes some work, then releases the wake lock:\n\n\n### Kotlin\n\n```kotlin\n@Throws(MyException::class)\nfun doSomethingAndRelease() {\n wakeLock.apply {\n try {\n acquire()\n doTheWork()\n } finally {\n release()\n }\n }\n}https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/misc/src/main/java/com/example/snippets/backgroundwork/WakeLockSnippetsKotlin.kt#L42-L52\n```\n\n### Java\n\n```java\nvoid doSomethingAndRelease() throws MyException {\n try {\n wakeLock.acquire();\n doTheWork();\n } finally {\n wakeLock.release();\n }\n}https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/misc/src/main/java/com/example/snippets/backgroundwork/WakeLockSnippetsJava.java#L27-L34\n```\n\n\u003cbr /\u003e\n\nMake sure to release wake locks as soon as they are no longer needed. For\nexample, if you use a wake lock to allow a background task to finish, make sure\nto release the lock as soon as the task finishes.\n\n### Key points about this code\n\nIn this example, the method `doTheWork()` might throw an exception. For this\nreason, the code releases the wake lock in the `finally` block, to make sure\nthe wake lock is released whether or not an exception is thrown. It's very\nimportant to make sure every wake lock you set is released, so you need to\ncheck every possible code path to make sure the wake lock isn't left active\non any of them.\n\nSee also\n--------\n\n- [Set a wake lock](/develop/background-work/background-tasks/awake/wakelock/set)"]]