How to improve battery efficiency of background work on Android
Summary
TLDRIn this video, Alice Yuan, a Developer Relations Engineer at Google, and Philip Cuadra from the Android Software Performance team, guide developers on understanding and optimizing app battery efficiency. They discuss the impact of background work on battery drain, the importance of using the right APIs, and best practices for background tasks. They also introduce Perfetto, a performance inspection tool, to analyze power and network usage, demonstrating how to improve battery life by avoiding common pitfalls.
Takeaways
- 🔋 Background battery drain is a significant issue for users, as seen in Bob's scenario where his device nearly dies despite infrequent use during the day.
- 🛠️ Developers play a crucial role in improving battery efficiency and preventing uninstalls by ensuring their apps do not contribute to unexpected battery drain.
- 🔄 Android has introduced several optimizations like Doze, Deep Doze, App Standby buckets, and Foreground Service Usage Restrictions to manage power consumption.
- 🤔 It's important for developers to select the right APIs for background tasks, considering factors like user value, awareness, and the necessity of immediate feedback.
- 📚 There are four main categories of APIs for background work: asynchronous APIs with lifecycle-aware components, optimized scheduling APIs, use-case-specific APIs, and Foreground Services.
- ❓ Developers should ask themselves key questions to determine the appropriate category of API to use, ensuring the app's background tasks are both efficient and user-centric.
- 🚀 Optimized scheduling APIs like WorkManager and JobScheduler should be used with best practices, such as setting constraints and batching work to minimize device wake-ups.
- 🚫 Avoid unnecessary use of wakelocks, especially from Foreground Services, as they can lead to inefficient battery usage if not managed correctly.
- 🔄 Foreground Services should only run for the duration of the user action and be stopped immediately once the action is paused or completed.
- 📈 Using performance inspection tools like Perfetto can help developers analyze power and network usage, identifying and fixing issues that lead to poor battery efficiency.
- 🛑 Identifying and addressing common pitfalls such as manually acquiring wakelocks without releasing them, running Foreground Services longer than needed, and making unnecessary network requests can greatly improve battery life.
Q & A
What is the main purpose of Alice's presentation?
-Alice's presentation aims to help developers understand how battery drain happens in the background and how to prevent their apps from causing unexpected battery drain, thereby improving app battery efficiency and preventing users from uninstalling their apps.
What are the major contributors to bad-battery user experiences according to Google's internal research?
-The major contributors to bad-battery user experiences are screen-off battery drain, with cellular Modem, CPU, Wi-Fi, and Bluetooth being the primary hardware components consuming the battery.
What role do developers play in managing energy consumption on devices?
-Developers have a significant influence on how successful a device is at managing energy consumption. They need to select the right APIs for background work and follow best practices to ensure their apps do not contribute to unnecessary battery drain.
What are the four categories of APIs available for doing work when an app is no longer visible?
-The four categories are: 1) using only asynchronous APIs along with lifecycle-aware components; 2) optimized scheduling APIs; 3) use-case-specific APIs; and 4) Foreground Service for scenarios to continue a user action.
Why should developers avoid using wakelocks unnecessarily, especially from a Foreground Service?
-Wakelocks prevent the CPU from sleeping when the screen is off, which can waste battery if managed inefficiently. Developers should ensure that wakelocks are only used when necessary and are released once the task is completed.
What are some best practices when using optimized scheduling APIs like WorkManager and JobScheduler?
-Best practices include declaring constraints to ensure tasks run during optimal scenarios, batching work together when possible, and using the expedited flag only for time-sensitive tasks while being aware of the quotas on runtime for expedited tasks.
How can developers ensure that their Foreground Services are used correctly and efficiently?
-Developers should avoid unnecessary wakelocks, ensure Foreground Services run only for the duration of the user action, and stop the service once the action is paused or completed. They should also ensure network requests are tied to lifecycle-aware components.
What is Perfetto and how can it help developers improve battery efficiency?
-Perfetto is a performance inspection tool that allows developers to manually analyze power and network usage on Android 14+ devices that support On Device Power Monitoring. It helps in identifying and fixing issues related to battery drain and network usage.
What are some of the key attributes developers should inspect in a Perfetto trace to optimize for battery drain?
-Key attributes include screen state, top app, device Suspend or Resume, battery_stats.audio, wakelock usage, network requests, and modem power usage.
How can developers leverage Perfetto to detect hard-to-find bugs related to battery efficiency?
-Developers can record a system trace using Perfetto, inspect the trace for key attributes related to battery and network usage, and identify issues such as unnecessary wakelocks, Foreground Services running longer than needed, and recurring network requests when the app is not visible.
What is the significance of the Android system's optimizations like Doze and Deep Doze, App Standby buckets, and Foreground Service Usage Restrictions in managing battery life?
-These optimizations help in reducing power consumption by managing how and when apps run in the background. They encourage developers to use the right tools and APIs, ensuring that battery life is preserved while still providing a good user experience.
Outlines
🔋 Introduction to Battery Drain and App Efficiency
Alice Yuan, a Developer Relations Engineer at Google, introduces the video with a scenario where Bob's device experiences unexpected battery drain despite infrequent usage. The video aims to educate developers on understanding and preventing background battery drain, emphasizing the importance of app battery efficiency to avoid uninstalls. Topics covered include the connection between background work and power consumption, the right APIs for background tasks, best practices for background work, and advanced skills for inspecting power and network usage. It highlights that screen-off battery drain is a significant issue, with cellular modem, CPU, Wi-Fi, and Bluetooth being the main contributors. Android's historical optimizations like Doze, Deep Doze, and App Standby buckets are mentioned, and developers are encouraged to use the right tools and APIs for energy-efficient app development.
🛠️ Selecting and Using the Right APIs for Background Work
The second paragraph delves into the selection and correct use of APIs for background tasks to improve battery efficiency. It categorizes background work APIs into asynchronous APIs with lifecycle-aware components, optimized scheduling APIs, use-case-specific APIs, and Foreground Services. A flowchart is suggested to determine the appropriate category for an app's background work. Best practices for using optimized scheduling APIs like WorkManager and JobScheduler are discussed, including setting constraints for optimal task execution times, avoiding the use of expedited tasks unless necessary, and using the getStopReason method for debugging. For Foreground Services, best practices include avoiding unnecessary wakelocks, ensuring services run only for the duration of user actions, and leveraging background exemptions wisely. The paragraph also advises checking alternative APIs for specific use cases to enhance runtime lifecycle management and battery optimization.
📊 Advanced Battery Efficiency Techniques with Perfetto
Philip Cuadra from the Android Software Performance team presents advanced techniques for inspecting and improving battery efficiency using the performance inspection tool Perfetto. He guides through the setup process for capturing a system trace on Android 14+ devices that support On Device Power Monitoring. The demonstration includes recording a trace for a media player app that continues audio playback in the background. Key attributes to inspect in the trace are highlighted, such as screen state, top app, device suspend/resume, and battery_stats.audio. Hard-to-detect bugs that affect battery efficiency are identified, such as unnecessary wakelocks, prolonged Foreground Service duration, and recurring network requests unrelated to media playback. The modem power track is used to correlate network activity with power usage, emphasizing the need to follow best practices to avoid such issues.
🚀 Recap and Conclusion on Enhancing Battery Efficiency
The final paragraph wraps up the video by recapping the key learnings about the connection between background work and power consumption, the significance of addressing screen-off battery drain, and the role of developers in selecting optimal APIs and following best practices. The importance of using tools like Perfetto for analyzing power and network usage is reiterated, and the improvements made after applying best practices are demonstrated through a revised system trace. The video concludes with a message that Android will continue to develop APIs that encourage energy efficiency and visible user value, ending with a positive note on the impact of these practices on user experience, as illustrated by Bob's improved battery life.
Mindmap
Keywords
💡Battery Drain
💡Background Work
💡Developer Relations Engineer
💡Screen-off Battery Drain
💡Hardware Components
💡Android System Optimizations
💡APIs
💡Foreground Service
💡Optimized Scheduling APIs
💡Perfetto
💡Lifecycle-Aware Components
💡Network Requests
Highlights
Alice Yuan introduces the issue of unexpected battery drain, like Bob's situation, and its impact on app uninstallation.
Background work and power consumption are connected, with screen-off battery drain being a significant contributor to poor user experiences.
Hardware components like the cellular modem, CPU, Wi-Fi, and Bluetooth are the main consumers of battery during screen-off periods.
Android has historically optimized battery consumption through features like Doze, Deep Doze, and App Standby buckets.
Developers play a crucial role in device energy management by selecting and using the right APIs for background tasks.
A flowchart is provided to help developers choose the appropriate category of APIs for background work.
Asynchronous APIs and lifecycle-aware components are recommended for tasks that do not need to continue once the app is backgrounded.
Foreground Services may be appropriate for user-initiated actions that require immediate feedback, such as media playback.
Optimized scheduling APIs are suggested for tasks that do not require user awareness, like periodic backups.
Alternative APIs can provide use-case-specific benefits and manage runtime lifecycle more efficiently.
Best practices for using optimized scheduling APIs include setting constraints for task execution and avoiding expedited tasks unless necessary.
Using Foreground Services efficiently involves avoiding unnecessary wakelocks and ensuring services run only for the duration of user actions.
Perfetto and On Device Power Monitoring can be used to manually analyze power and network usage for further optimization.
Setup instructions for capturing a system trace with Perfetto are provided for detailed analysis of app performance.
Key attributes to inspect in a Perfetto trace include screen state, top app, device suspend/resume, and network tracing.
Hard-to-detect bugs in app behavior can lead to poor battery efficiency, as demonstrated through a media player example.
Correct use of APIs and adherence to best practices can resolve issues like unnecessary wakelocks and prolonged foreground service runtime.
Improved app behavior results in better device suspend mode entry, reduced wakelock duration, and optimized network request scope.
Ongoing tooling improvements in Perfetto and Android Studio aim to enhance performance debugging capabilities for developers.
The presentation concludes with a recap of learnings and a reminder of the importance of developer efforts in improving battery efficiency.
Transcripts
[MUSIC PLAYING]
ALICE YUAN: Imagine this situation.
Bob is spending the day out with some friends and starts the day
with a fully charged device.
During the whole day, he infrequently uses his device.
However, at the end of the day, when
he proceeds to look up directions to go home,
the phone is near dead.
Where did that battery go?
Hi, I'm Alice, a Developer Relations Engineer at Google.
And I will be helping you understand
how battery drain happens in the background
so that you can prevent your app from being
the cause of unexpected battery drain, such as Bob's situation.
Improving your app's battery efficiency
will also prevent users like Bob from uninstalling your app.
In this video, we will go over the following topics--
How are background work and power consumption
connected, what are the right APIs to use,
and what are the best practices when doing background work,
how to level up your skills further by inspecting your apps
power and network usage.
You may be wondering, doesn't battery drain mostly happen
when the device is awake?
This is true.
However, based on an internal research and testing,
a major contributor to bad-battery user experiences
is screen-off battery drain.
When looking at screen-off battery drain,
our internal metrics show that the battery is consumed most
by the following hardware components-- cellular Modem,
followed by the CPU, then Wi-Fi and Bluetooth combined.
Later, we will discuss how to analyze power drain
of these hardware components.
Another question you might be thinking--
shouldn't the Android system be responsible for optimizing
the usage?
Yes.
Historically, Android has optimized the consumption
in the following ways--
Doze and Deep Doze, App Standby buckets, App Cached State,
Foreground Service Usage Restrictions, and more.
- Despite the number of optimizations and APIs
we've introduced, they are only effective
if you're also using the right tool in your toolbox.
That's what this talk is about.
Developers like you have a large influence
on how successful the device is at managing energy consumption.
Let's dive into how to do that.
When starting out on your journey
to improve your app's battery efficiency,
the first question to ask yourself
is, have I selected the right tool,
the most optimal API for my feature
to run in the background?
The APIs available for doing work
once the app is no longer visible
can be split into the following four categories--
one, using only asynchronous APIs along
with lifecycle-aware components; two, optimized scheduling APIs;
three, use-case-specific APIs; and lastly, for scenarios
to continue a user action, as the name suggests,
Foreground Service.
Here's a flow chart to ask yourself to understand which
category you should be using.
Does the device need to continue once the app has
been backgrounded?
For example, if you start fetching a news
feed for your app, finishing this work after the user
leaves the app does not provide user value.
You should use asynchronous APIs along
with lifecycle-aware components to cancel the work
once the user leaves the app.
Is the user aware of this background task?
If this is a user initiating the action
or it requires immediate user feedback,
Foreground Services may be appropriate.
For example, if a user is playing music and wants
the music to continue playing once the app is
in the background, you can use a Foreground Service with the type
''media playback''.
For short critical tasks, such as completing a payment,
you can use the Foreground Service with the type
''short service.''
If the user is not aware of the work
or does not require feedback, you
should instead leverage optimized scheduling APIs.
For example, doing a periodic backup of local content
to the server does not require user awareness.
These are great ways to optimize app battery that
also enhance user experience.
Before deciding on using a Foreground Service,
is there an alternative API for your use case?
You can find in our Foreground Service type documentation
alternative APIs that help you manage the runtime lifecycle
or trigger the work in more battery optimal ways.
The alternative APIs also provide
use-case-specific benefits.
The most common scenarios for using alternative APIs
are, using user-initiated data transfers to do large downloads
or uploads, instead of creating a data-sync Foreground Service.
This API has the ability to retry
if the transfers fail and will execute only
during network availability.
Also, using companion device manager for Bluetooth pairing
and data transfer, instead of using
connected-device foreground service.
Deciding the right tool is step 1 of the journey
to improve battery efficiency.
Step 2 is making sure that you're also
using the tool correctly.
Let's cover best practices of two of the most common options.
Using optimized scheduling APIs and using Foreground Service.
Here are three best practices when
using optimized scheduling APIs that improve battery efficiency.
These tips apply for both WorkManager and JobScheduler.
When you go to sleep for the night,
would you rather be woken up 16 times, every 30 minutes,
or would you rather be woken up once
and get everything done all at once?
The device is similar to the user, the more
times the device is woken up, the more energy is consumed.
You should declare a constraints to ensure that the task runs
in more optimal scenarios and when possible,
batch the work together.
Setting constraints, for example, executing
while charging or executing on an unmetered network,
help ensure that the task executes
during less-expensive windows of time.
The charging constraint is especially recommended
on wear devices to minimize battery drain.
By default, the system chooses when
to run your task when it is most efficient.
It may not run immediately when you schedule the task
and the app is not in a visible state.
You can exempt this optimization by using the expedited flag.
However, you should only do so if the task is time sensitive.
There are quotas on how much runtime expedited tasks can
run for since expedited tasks drain more energy
than the default running task.
A valid scenario where you can use the set expedited flag
is for a task that should happen as a result
of a high-priority FCM.
An invalid scenario is to override system optimizations.
The default task will execute at a system
optimal time once the define constraints are met.
Use the getStopReason method to find out
how your task was stopped.
For example, if your task often gets the stop_reason_timeout,
there could be an edge case that should be canceled
and requires further debugging.
We encourage you to track this data via your analytics engine
to help you detect how often your task is
stopped by the system.
Furthermore, if your task times out too often,
the system can put your application
into a restricted state.
Here are three best practices when
using Foreground Services that improve battery efficiency.
Avoid using wakelocks unnecessarily, especially
from a Foreground Service.
Wakelocks are a way to prevent the CPU from sleeping
when the screen is off.
However, they can be tricky to manage
and can waste battery when managed inefficiently.
Here are some questions to consider when using a wakelock.
Are you already using an API that
is an alternative to holding a wakelock?
For example, if you're using WorkManager, JobScheduler
or ExoPlayer, you do not need to acquire a wakelock.
Does the use case require the device
to perform even when the screen is off?
If you only need to do something periodically
and while the device is awake, a wakelock
is not necessary, for example, if you're using a Foreground
Service to intermittently communicate
with an external device and there
is no user value to this communication
while the screen is off.
Foreground Services should only be
used for the duration of the user action.
Once the action is paused or completed,
you should stop the Foreground Service.
Running the service for longer than the user action
can allow for other unrelated asynchronous
work to keep running and unexpectedly consume battery.
For example, if you're running a Media Playback Foreground
Service for playing music in the background,
once the user has paused the music,
you should immediately stop the Foreground Service.
You can verify that the Foreground Service has
been stopped in the Task Manager available on devices running
Android 13 and higher.
Foreground Services are intended to continue
a user-initiated action.
Are you leveraging a background exemption
to start the service when the app isn't visible?
For example, you may be using BOOT_COMPLETED broadcast
receiver exemption to start a Foreground Service immediately
after the device has restarted.
We strongly recommend waiting until the user has indicated
intention to restart the action to use this Foreground
Service again.
We are also adding restrictions to which Foreground Services can
start from BOOT_COMPLETED when targeting Android 15.
If you're interested in learning more
about best practices for either optimized scheduling
APIs or Foreground Service, you can
consult our developer documentation linked
in the video description.
Now I'll hand it over to my colleague Philip to share tips
on how to improve battery efficiency using Perfetto.
PHILIP CUADRA: Hi.
I'm Philip Cuadra from the Android Software Performance
team.
We're at the final step of our journey
to bettering battery efficiency, inspecting our handiwork.
If you want to level up further, you can use the performance
inspection tool Perfetto and an Android 14+ device that supports
On Device Power Monitoring, such as Pixel 6 and subsequent Pixel
devices to manually analyze power and network usage.
First, let's go through the setup instructions.
There are multiple methods of getting the system trace.
We recommend manually capturing a trace
through Perfetto using the custom record settings.
First, go to ui.perfetto.dev.
It will look something like this.
Go to ''Record a new trace'' to get started.
You will need to make some changes for the recording
configuration.
Set the max duration to support the full duration
of testing your feature.
We have it set to five minutes for this demo.
In power probe, on the side menu,
turn on "Battery drain & power rails."
Go to "Android apps and services'' probe and turn
on "Atrace userspace annotations."
We've selected ''activity manager," ''audio," "network"
and "power management" annotations.
Scroll down to turn on "Network Tracing" in the Perfetto UI.
This is a feature that is launching on ODPM-compatible
Android 14 devices.
PHILIP CUADRA: You can start recording the trace
once you've connected your ADB device.
There is a lot to learn about Perfetto
that we won't be able to cover as a part of this talk.
If you're keen to learn more, watch the Performance Debugging
MAD skills series on YouTube.
For this talk, we'll profile a media player
that continues to play audio even
if the user backgrounds the application
or turns the screen off.
In this flow, I'll start playing music,
switch to a different app, and eventually pause the music
and turn off the device screen.
However, there are a few hard-to-detect bugs
that are resulting in poor battery efficiency.
Now that we've profiled the major flows of our app,
let's stop the trace and inspect the results.
Once you've opened the trace, it will look something like this.
We're going to focus on a few attributes
to inspect as part of this trace.
Use the pen icon by hovering over the corresponding track
to pin the important attributes to the top of our trace.
I've gone ahead and pinned some key info.
You can pause the video now to search and find
the same attributes and pin it to your Perfetto trace.
Let's break down these key attributes.
The screen state indicates whether or not
the screen is on or off.
In our trace, the device's screen eventually turns off.
The top app indicates, what is the visible app
the user currently has on the device?
The device Suspend or Resume indicates
if the device is in suspend mode, which
helps conserve battery.
Note that the device seems to never go
into suspend mode on our device.
Here's where things get interesting.
We are able to use battery_stats.audio to help us
understand when the audio track is being utilized.
We can see that despite our expectations,
the foreground app shows that our declared
Foreground Service continues to run even after the music has
stopped playing.
Also, in Device State--
Long wakelock, we can see that there
are two wakelocks being held--
audio mix and the media wakelock,
which continues to run even after the audio
is no longer playing.
There is also repeating network requests
coming from the app denoted in the light-green indicators that
happen about every 20 seconds, even after the audio is
no longer streaming.
This request is not related to media playback,
so it shouldn't be happening once the app is
no longer visible.
You can click on each network indicator
to better understand where the request came from.
The indicators of different colors
are coming from other applications.
If you take a look at the modem power track,
you will notice a corresponding bump in power usage.
Remember this chart?
Earlier in the talk, Alice mentioned
that cellular modem, which corresponds to the modem power
track, is the device component that drains
the most amount of power.
If I had followed best practices,
I wouldn't have encountered these issues.
Pause this video if you want to take a moment
to think about which best practices apply
to this scenario.
Number one, we're manually acquiring a wakelock
and failing to release it once the media stops playing.
As seen in long wakelocks, ExoPlayer library
was already holding a wakelock on our behalf.
It is unnecessary in this scenario
to manually acquire a wakelock.
Number 2, the Foreground Service continues
to run even after the media is stopped.
The Foreground Service should be stopped as soon
as the media stops playing.
Number 3, the 20-second recurring network activity is
tied to the application scope, instead of the view or activity
scope, which causes the network request to keep happening even
when the app is no longer visible.
This is why it's so important to ensure
your network requests are tied to lifecycle-aware components.
Here is another trace now that we've fixed the issues.
Notice how the device is able to go into suspended mode,
indicated by the suspend resume track.
Also, the wakelock and foreground app duration
are much shorter, running only for the duration of the media
session.
We also don't see any additional network
requests coming from the app once the app is not
playing media.
When looking at the modem power track,
we no longer see the corresponding power-drain bump.
We're continuing to make improvements
on tooling so that you can better debug performance,
both within Perfetto and in Android Studio.
If you're interested in debugging power
on Android Studio, check out the I/O talk that Mayank is giving,
actionable app profiling in Android Studio.
Now, I'll hand it back to Alice to wrap things up.
Thanks, Philipp.
Wow, that was quite a journey we went on.
Let's recap what we learned.
We learned about how background work and power consumption
are connected.
A major contributor to bad battery experiences
is actually screen off battery drain.
Developers should not solely rely on system optimizations
to improve battery life.
We learned about how to select the most optimal APIs
for running work in the background using this flowchart,
as well as best practices using optimized scheduling
APIs and Foreground Services.
Finally, we upleveled our skills by learning
about how to record a system trace and inspect
the trace using Perfetto to optimize for network
usage and battery drain.
Android will continue to optimize and build
APIs that encourage developers to shift energy away
from invisible use cases and towards customer visible use
cases that provide measurable value.
Remember Bob?
Thanks to all of your efforts, his device
is draining far less battery, and he's able to get home.
That's all from me.
Thanks for watching.
[MUSIC PLAYING]
تصفح المزيد من مقاطع الفيديو ذات الصلة
Battery Saving iPhone Tips That (Actually) Work 🤯🔋 [2024]
iPhone 15 Pro - First 25 Things To Do! (Tips & Tricks)
Poco X6 Neo 5g vs Realme Narzo 70 5g vs Moto G64 5g vs Vivo T3x 5g : Battery Test.
How to IMPROVE Google Pixel battery life | Simple tips!
Best Laptop CPU? AMD Ryzen AI 9 HX 370 vs Intel Core Ultra 9 185H
iOS 18 Beta 3 Battery Life and Performance Review
5.0 / 5 (0 votes)