確保獲取和釋放 Wake Lock 時,盡可能使用簡單的邏輯。如果 Wake Lock 邏輯和複雜的狀態機器、逾時、執行程式集區或回呼事件有關,那麼一旦這個邏輯裡有任何不明顯的錯誤,就可能會導致 Wake Lock 保留時間超出預期。這種錯誤的診斷和偵錯作業相當困難。
確認 Wake Lock 一律會釋放
如果您使用 Wake Lock,請務必確保獲取的每個 Wake Lock 都已正確釋放。這看似簡單,但其實不然。舉例來說,下列程式碼有問題:
Kotlin
@Throws(MyException::class)fundoSomethingAndRelease(){wakeLock.apply{acquire()doTheWork()// can potentially throw MyExceptionrelease()// does not run if an exception is thrown}}
Java
voiddoSomethingAndRelease()throwsMyException{wakeLock.acquire();doTheWork();// can potentially throw MyExceptionwakeLock.release();// does not run if an exception is thrown}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-08-27 (世界標準時間)。"],[],[],null,["Using a wake lock can impair device performance. If you need to use a wake\nlock, it's important to do it properly. This document covers some best practices\nthat can help you avoid common wake lock pitfalls.\n| **Note:** Creating and holding wake locks can have a dramatic impact on the device's battery life. You shouldn't use wake locks if there are any suitable alternatives. For other options, see the [Keep the device awake](/develop/background-work/background-tasks/awake) documentation. If you do need to use a wake lock, make sure to hold it for as short a time as possible.\n\nName the wake lock properly\n\nWe recommend including your package, class, or method name in the wakelock\ntag. That way, if an error occurs, it's easier to find the location in your\nsource code where the wake lock was created. Here are some additional tips:\n\n- Leave out any personally identifying information (PII) in the name, such as an email address. If the device detects PII in the wake lock tag, it logs `_UNKNOWN` instead of the tag you specified.\n- Don't get the class or method name programmatically, for example by calling `getName()`. If you try to get the name programmatically, it might get obfuscated by tools like Proguard. Instead use a hard-coded string.\n- Don't add a counter or unique identifiers to wake lock tags. The code that creates a wake lock should use the same tag every time it runs. This practice enables the system to aggregate each method's wake lock usage.\n\nMake sure your app is visible in the foreground\n\nWhile a wake lock is active, the device is using power. The device's user\nshould be aware that this is going on. For this reason, if you're using a\nwake lock, you should display some notification to the user.\nIn practice, this means you should get and hold the wakelock in a\n[foreground service](/develop/background-work/services/fgs). Foreground services are required to display\na notification.\n\nIf a foreground service isn't the right choice for your app,\nyou probably shouldn't be using a wake lock, either. See the\n[Choose the right API to keep the device awake](/develop/background-work/background-tasks/awake)\ndocumentation for other ways to do work while your app isn't in the foreground.\n\nKeep the logic simple\n\nMake sure the logic for acquiring and releasing wake locks is as simple as\npossible. When your wake lock logic is tied to complex state machines, timeouts,\nexecutor pools, or callback events, any subtle bug in that logic can cause the\nwake lock to be held longer than expected. These bugs are difficult to diagnose\nand debug.\n\nCheck that the wake lock is always released\n\nIf you use a wake lock, you must make sure that every wake lock you acquire\nis properly released. This isn't always as easy as it sounds. For example,\nthe following code has a problem: \n\nKotlin \n\n @Throws(MyException::class)\n fun doSomethingAndRelease() {\n wakeLock.apply {\n acquire()\n doTheWork() // can potentially throw MyException\n release() // does not run if an exception is thrown\n }\n }\n\nJava \n\n void doSomethingAndRelease() throws MyException {\n wakeLock.acquire();\n doTheWork(); // can potentially throw MyException\n wakeLock.release(); // does not run if an exception is thrown\n }\n\nThe problem here is that the method `doTheWork()` can throw the exception\n`MyException`. If it does, the `doSomethingAndRelease()` method propagates\nthe exception outward, and it never reaches the `release()` call. The result\nis that the wake lock is acquired but not released, which is very bad.\n\nIn the corrected code, `doSomethingAndRelease()` makes sure to release the\nwake lock even if an exception is thrown: \n\nKotlin \n\n @Throws(MyException::class)\n fun doSomethingAndRelease() {\n wakeLock.apply {\n try {\n acquire()\n doTheWork()\n } finally {\n release()\n }\n }\n }\n\nJava \n\n void doSomethingAndRelease() throws MyException {\n try {\n wakeLock.acquire();\n doTheWork();\n } finally {\n wakeLock.release();\n }\n }"]]