フォアグラウンド サービスがアプリに適していない場合は、ウェイクロックも使用しない方がよいでしょう。アプリがフォアグラウンドにない間に作業を行うその他の方法については、デバイスを起動状態に保つための適切な API の選択に関するドキュメントをご覧ください。
ロジックをシンプルにする
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 UTC。"],[],[],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 }"]]