A lot of the content material of this publish can also be obtainable in video format, go give it a watch!
Battery life is a vital facet of consumer expertise and wake locks play a significant position. Are you utilizing them excessively? On this weblog publish we’ll discover what wake locks are, what are some greatest practices for utilizing them and how one can higher perceive your individual app’s habits with the Play Console metric.
Extreme partial wake lock utilization in Android Vitals
The Play Console now screens battery drain, with a give attention to extreme partial wake lock utilization, as a key efficiency indicator.
This characteristic elevates the significance of battery effectivity alongside present core metric stability indicators: extreme user-perceived crashes and ANRs. At the moment, an app exceeding the brink is not going to be much less discoverable on Google Play.
For cell units, the Android vitals metric applies to non-exempted wake locks acquired whereas the display is off and the app is within the background or working a foreground service. Android vitals considers partial wake lock utilization extreme if:
Wake locks are held for a minimum of two hours inside a 24-hour interval.
It impacts greater than 5% of your app’s periods, averaged over 28 days.
Wake locks created by audio, location, and JobScheduler consumer initiated APIs are exempted from the wake lock calculation.
Understanding wake locks
A wake lock is a mechanism that permits an app to maintain a tool’s CPU working even when the consumer is not actively interacting with it.
A partial wake lock retains the CPU working even when the display is off, stopping the CPU from coming into a low-power “droop” state. A full wake lock retains each the display and the CPU working.
There are 2 strategies partial wake locks are acquired:
The app manually acquires and releases the wake lock utilizing PowerManager APIs for a particular use case, usually that is acquired along side a Foreground Service – a platform lifecycle API supposed for user-perceptible operation.
Alternatively, the wake lock is acquired by one other API, and attributed to the app resulting from utilization of the API, extra on this in the perfect practices part.
Whereas wake locks are vital for duties like finishing a user-initiated obtain of a giant file, their extreme or improper use can result in vital battery drain. We have seen instances the place apps maintain wake locks for hours or fail to launch them correctly, resulting in consumer complaints about vital battery drain even after they’re not interacting with the app.
Finest Practices for Wake Lock Utilization
Earlier than we go over learn how to debug extreme wake lock utilization, make sure you’re following wake lock greatest practices.
Think about these 4 vital questions.
Earlier than contemplating buying a guide partial wake lock, observe this decision-making flowchart:
Flowchart to resolve when to manually purchase a wake lock
Does the display want to remain on?
Is the appliance working a foreground service?
Is it detrimental to the consumer expertise if the gadget suspends?
No: As an illustration, updating a notification after the gadget wakes up does not require a wake lock.
Sure: If it’s vital to stop the gadget from suspending, like ongoing communication with an exterior gadget, proceed.
Is there already an API conserving the gadget awake in your behalf?
You’ll be able to leverage the documentation Determine wake locks created by different APIs to establish situations the place wake locks created by different APIs to establish situations the place wake locks are created by different APIs corresponding to LocationManager.
If no APIs exist, proceed to the ultimate query.
If you happen to’ve answered all these questions and decided no different exists, you need to proceed with manually buying a wake lock.
2. Are you naming the wake lock appropriately?
When manually buying wake locks, correct naming is necessary for debugging:
Pass over any Personally Identifiable Info (PII) within the identify like e-mail addresses. If PII is detected, the wake lock is logged as _UNKNOWN, hindering debugging.
Do not identify your wake lock programmatically utilizing class or technique names, as these will be obfuscated by instruments like Proguard. As an alternative, use a hard-coded string.
Don’t add counters or distinctive identifiers to wake lock tags. The identical tag must be used each time the wake lock runs to permit the system to mixture utilization by identify, making irregular habits simpler to detect.
3. Is the acquired wake lock all the time launched?
If you happen to’re buying a wake lock manually, make sure the wake lock launch all the time executes. Failing to launch a wake lock may cause vital battery drain.
For instance, if an uncaught exception is thrown throughout processingWork(), the launch() name may by no means occur. As an alternative, you need to use a try-finally block to ensure the wake lock is launched, even when an exception happens.
Moreover, you may add a timeout to the wake lock to make sure it releases after a particular interval, stopping it from being held indefinitely.
enjoyable processingWork() { wakeLock.apply { strive { purchase(60 * 10 * 1000) // timeout after 10 minutes doTheWork() } lastly { launch() } } }
4. Are you able to cut back the wake-up frequency?
For periodic information requests, decreasing how usually your app wakes up the gadget is vital to battery optimization. Some examples of decreasing wake-up frequency embrace:
WorkManager: Enhance the periodic interval in PeriodicWorkRequests.
SensorManager: Leverage batching by specifying maxReportLatencyMs when registering the listener.
Fused Location Supplier:
You’ll be able to view extra particulars within the wake lock greatest practices documentation.
Debugging extreme wake lock utilization
Even with the perfect intentions, extreme wake lock utilization can happen. In case your app is flagged within the Play Console, here is learn how to debug it:
You’ll be able to establish worker-held wake locks with this wake lock identify:
*job*/<package_name>/androidx.work.impl.background.systemjob.SystemJobService
The total checklist of variations of worker-held wake lock names is on the market in documentation. To debug these wake locks, you need to use Background Activity Inspector to debug domestically, or leverage getStopReason to debug points within the subject.
Android Studio Background Activity InspectorDisplay seize of the Background Activity Inspector, the place it has been in a position to establish a employee “WeatherSyncWorker” that has regularly retried and failed.
For native debugging of WorkManager points, use this software on an emulator or related gadget (API degree 26+). It reveals an inventory of staff and their statuses (completed, executing, enqueued), permitting you to examine particulars and perceive employee chains.
As an illustration, it may possibly reveal if a employee is regularly failing or retrying resulting from hitting system limitations.
See Background Activity Inspector documentation for extra particulars.
WorkManager getStopReason
For in-field debugging of staff with extreme wake locks, use WorkInfo.getStopReason() on WorkManager 2.9.0+ or for JobScheduler, JobParameters.getStopReason() obtainable on SDK 31+.
This API helps log the rationale why a employee stopped (e.g., STOP_REASON_TIMEOUT, STOP_REASON_QUOTA), pinpointing points like frequent timeouts resulting from exhausting runtime length.
backgroundScope.launch { WorkManager.getInstance(context) .getWorkInfoByIdFlow(workRequest.id) .acquire { workInfo -> logStopReason(workRequest.id, workInfo?.stopReason) } }
Debugging different kinds of extreme wake locks
For extra advanced situations involving manually held wake locks or APIs holding the wake lock, we advocate you utilize system hint assortment to debug.
System hint assortment
A system hint is a robust debugging software that captures an in depth report of system exercise over a interval, offering insights into CPU state, thread exercise, community exercise, and battery-related metrics like job length and wake lock utilization.
You’ll be able to seize a system hint utilizing a number of strategies:
Allow “energy:PowerManagement” Atrace class within the Perfetto UI underneath the Android apps & svcs tab.
Whatever the chosen technique, it is essential to make sure that you’re amassing the “energy:PowerManagement” Atrace class to allow viewing of gadget state tracks.
Perfetto UI inspection and SQL evaluation
System traces will be opened and inspected within the Perfetto UI. Once you open the hint, you will notice a visualization of assorted processes on a timeline. The tracks we can be centered on on this information are those underneath “Gadget State”.
Pin the tracks underneath “Gadget State” corresponding to “High app”, “Display state”, “Lengthy Wake locks”, and “Jobs” tracks to visually establish long-running wake lock slices.
Every block lists the identify of the occasion, when the occasion began, and when it ended. In Perfetto, that is known as a slice.
For scalable evaluation of a number of traces, you need to use Perfetto’s SQL evaluation. A SQL question can discover all wake locks sorted by length, serving to establish the highest contributors to extreme utilization.
Right here’s an instance question summing all of the wake lock tags that occurred within the system hint, ordered by whole length:
SELECT slice.identify as identify, observe.identify as track_name, SUM(dur / 100000) as total_dur_ms FROM slice JOIN observe ON slice.track_id = observe.id WHERE observe.identify = 'WakeLocks' GROUP BY slice.identify, observe.identify ORDER BY total_dur_ms DESC
Use ProfilingManager for in-field hint assortment
For hard-to-reproduce points, ProfilingManager (added in SDK 35) is a programmatic API that permits builders to gather system traces within the subject with begin and finish triggers. It affords extra management over the beginning and finish set off factors for profile assortment and enforces system-level fee limiting to stop gadget efficiency impression.
Take a look at the ProfilingManager documentation for additional steps on learn how to implement in subject system hint assortment which embrace learn how to programmatically seize a hint, analyze profiling information, and use native debug instructions.
The system traces collected utilizing ProfilingManager will look much like those collected manually, however system processes and different app processes are redacted from the hint.
Conclusion
The extreme partial wake lock metric in Android vitals is just a small a part of our ongoing dedication to supporting builders in decreasing battery drain and enhancing app high quality.
By understanding and correctly implementing wake locks, you may considerably optimize your app’s battery efficiency. Leveraging different APIs, adhering to wake lock greatest practices, and utilizing highly effective debugging instruments corresponding to Background Activity Inspector, system traces and ProfilingManager are key to making sure your app’s success on Google Play.

