釋放 Wake Lock
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
本頁說明如何釋放應用程式持有的喚醒鎖定。應用程式使用完畢後,請務必立即釋放喚醒鎖定,以免耗盡電池電量。
釋放有效的 Wake Lock
如要釋放作用中的喚醒鎖定,請呼叫其 release()
方法。這樣做會將 CPU 的聲明發布至 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();
}
}
請務必在不再需要時立即釋放 Wake Lock。舉例來說,如果您需要使用 Wake Lock 才能完成背景工作,請確保工作結束後就會釋放 Wake Lock。
這組代碼的重點
在這個範例中,方法 doTheWork()
可能會擲回例外狀況。因此,程式碼會在 finally
區塊中釋放喚醒鎖定,確保無論是否擲回例外狀況,喚醒鎖定都會釋放。請務必釋放您設定的每個喚醒鎖定,因此您需要檢查所有可能的程式碼路徑,確保喚醒鎖定不會在任何路徑上保持啟用狀態。
另請參閱
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-08-24 (世界標準時間)。
[null,null,["上次更新時間: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)"]]