절전 모드 해제 잠금을 사용하면 기기 성능이 저하될 수 있습니다. 절전 모드 해제 잠금을 사용해야 하는 경우 올바르게 사용하는 것이 중요합니다. 이 문서에서는 일반적인 절전 모드 문제점을 방지하는 데 도움이 되는 몇 가지 권장사항을 다룹니다.
wake lock의 이름을 적절하게 지정
패키지, 클래스 또는 메서드 이름을 wakelock 태그에 포함하는 것이 좋습니다. 이렇게 하면 오류가 발생할 경우 웨이크 락이 생성된 소스 코드의 위치를 더 쉽게 찾을 수 있습니다. 다음은 몇 가지 추가적인 도움말입니다.
이름에서 이메일 주소와 같은 개인 식별 정보(PII)를 제외하세요. 기기에서 웨이크 락 태그에 PII를 감지하면 지정한 태그 대신 _UNKNOWN을 로깅합니다.
프로그래매틱 방식으로 클래스 또는 메서드 이름을 가져오지 마세요(예: getName() 호출). 프로그래매틱 방식으로 이름을 가져오려고 하면 Proguard와 같은 도구로 난독화될 수 있습니다. 대신 하드 코딩된 문자열을 사용하세요.
wake lock 태그에 카운터 또는 고유 식별자를 추가하지 마세요. 웨이크 락을 만드는 코드는 실행될 때마다 동일한 태그를 사용해야 합니다.
이 방법을 사용하면 시스템이 각 메서드의 절전 모드 해제 잠금 사용량을 집계할 수 있습니다.
앱이 포그라운드에 표시되는지 확인
절전 모드 해제 잠금이 활성 상태인 동안 기기는 전원을 사용합니다. 기기 사용자는 이 사실을 알고 있어야 합니다. 따라서 절전 모드 해제 잠금을 사용하는 경우 사용자에게 알림을 표시해야 합니다.
실제로 이는 포그라운드 서비스에서 웨이크락을 획득하고 유지해야 함을 의미합니다. 포그라운드 서비스는 알림을 표시해야 합니다.
포그라운드 서비스가 앱에 적합하지 않다면 절전 모드 해제 잠금도 사용하지 않는 것이 좋습니다. 앱이 포그라운드에 있지 않을 때 작업을 실행하는 다른 방법은 기기를 절전 모드로 전환하지 않도록 올바른 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}}
자바
voiddoSomethingAndRelease()throwsMyException{wakeLock.acquire();doTheWork();// can potentially throw MyExceptionwakeLock.release();// does not run if an exception is thrown}
여기서 문제는 doTheWork() 메서드가 MyException 예외를 발생시킬 수 있다는 것입니다. 예외가 발생하면 doSomethingAndRelease() 메서드가 예외를 외부로 전파하므로 release() 호출에 도달하지 않습니다. 결과적으로 절전 모드 해제 잠금이 획득되지만 해제되지 않으며 이는 매우 좋지 않습니다.
수정된 코드에서 doSomethingAndRelease()는 예외가 발생하더라도 절전 모드 해제 잠금을 해제합니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-08-21(UTC)
[[["이해하기 쉬움","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-21(UTC)"],[],[],null,["# Follow wake lock best practices\n\nUsing 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---------------------------\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-----------------------------------------------\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---------------------\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-------------------------------------------\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\n### Kotlin\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\n### Java\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\n### Kotlin\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\n### Java\n\n void doSomethingAndRelease() throws MyException {\n try {\n wakeLock.acquire();\n doTheWork();\n } finally {\n wakeLock.release();\n }\n }"]]