How to improve battery efficiency of background work on Android

Android Developers
16 May 202418:14

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

00:00

🔋 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.

05:01

🛠️ 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.

10:01

📊 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.

15:02

🚀 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

Battery drain refers to the depletion of a device's battery power, which can be accelerated by various factors including software usage. In the video's context, it is the primary issue being addressed, particularly focusing on unexpected battery drain that occurs even when the device is infrequently used, as illustrated by Bob's situation.

💡Background Work

Background work encompasses tasks that an app performs even when it is not actively being used by the user. The video discusses how such tasks can contribute to battery drain and emphasizes the importance of managing these tasks efficiently to conserve battery life.

💡Developer Relations Engineer

A Developer Relations Engineer, as represented by Alice in the video, is a professional who bridges the gap between software developers and the technologies or platforms they work with. Alice's role is to guide developers on how to optimize their apps to prevent battery drain.

💡Screen-off Battery Drain

Screen-off battery drain is the consumption of battery power when the device's screen is not in use. The video highlights that this is a major contributor to poor battery experiences, indicating that significant battery usage occurs even when the device is not actively being viewed or interacted with.

💡Hardware Components

Hardware components in the context of the video refer to the physical parts of the device that contribute to battery consumption, such as the cellular modem, CPU, Wi-Fi, and Bluetooth. The script mentions these as the primary consumers of battery when the screen is off.

💡Android System Optimizations

Android system optimizations are features built into the Android operating system to manage and reduce power consumption. The video references several of these, including Doze and Deep Doze modes, App Standby buckets, and restrictions on Foreground Service usage, which are designed to enhance battery efficiency.

💡APIs

APIs, or Application Programming Interfaces, are sets of routines and protocols that allow different software applications to communicate with each other. In the video, the correct use of APIs is emphasized as a key factor in preventing unnecessary battery drain in apps.

💡Foreground Service

A Foreground Service in Android is a component that runs in the foreground and is aware of system optimizations. The video discusses the appropriate use of Foreground Services and how they should be used to continue user actions, providing examples such as media playback.

💡Optimized Scheduling APIs

Optimized scheduling APIs are tools that allow developers to schedule tasks in a way that is considerate of the device's power state and user activity. The video provides best practices for using these APIs, such as batching work together and setting constraints for execution during optimal times.

💡Perfetto

Perfetto is a performance analysis and tracing tool used for Android applications. In the video, it is introduced as a means for developers to inspect their app's power and network usage, helping to identify and rectify issues that could lead to battery drain.

💡Lifecycle-Aware Components

Lifecycle-aware components are parts of an app that are designed to respond to changes in the app's lifecycle, such as when it moves to the background or the device goes to sleep. The video stresses the importance of using these components to manage tasks and prevent battery drain when the app is not in use.

💡Network Requests

Network requests are actions made by an app to communicate with a server or other network resources. The video points out that improper management of network requests, such as making them too frequently or without regard to the app's lifecycle, can contribute to battery drain.

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

play00:00

[MUSIC PLAYING]

play00:04

ALICE YUAN: Imagine this situation.

play00:06

Bob is spending the day out with some friends and starts the day

play00:09

with a fully charged device.

play00:11

During the whole day, he infrequently uses his device.

play00:14

However, at the end of the day, when

play00:16

he proceeds to look up directions to go home,

play00:19

the phone is near dead.

play00:20

Where did that battery go?

play00:22

Hi, I'm Alice, a Developer Relations Engineer at Google.

play00:26

And I will be helping you understand

play00:28

how battery drain happens in the background

play00:30

so that you can prevent your app from being

play00:32

the cause of unexpected battery drain, such as Bob's situation.

play00:37

Improving your app's battery efficiency

play00:39

will also prevent users like Bob from uninstalling your app.

play00:44

In this video, we will go over the following topics--

play00:47

How are background work and power consumption

play00:50

connected, what are the right APIs to use,

play00:53

and what are the best practices when doing background work,

play00:57

how to level up your skills further by inspecting your apps

play01:01

power and network usage.

play01:02

You may be wondering, doesn't battery drain mostly happen

play01:06

when the device is awake?

play01:08

This is true.

play01:09

However, based on an internal research and testing,

play01:12

a major contributor to bad-battery user experiences

play01:15

is screen-off battery drain.

play01:17

When looking at screen-off battery drain,

play01:20

our internal metrics show that the battery is consumed most

play01:23

by the following hardware components-- cellular Modem,

play01:26

followed by the CPU, then Wi-Fi and Bluetooth combined.

play01:30

Later, we will discuss how to analyze power drain

play01:33

of these hardware components.

play01:36

Another question you might be thinking--

play01:38

shouldn't the Android system be responsible for optimizing

play01:42

the usage?

play01:43

Yes.

play01:44

Historically, Android has optimized the consumption

play01:47

in the following ways--

play01:48

Doze and Deep Doze, App Standby buckets, App Cached State,

play01:53

Foreground Service Usage Restrictions, and more.

play01:57

- Despite the number of optimizations and APIs

play02:00

we've introduced, they are only effective

play02:03

if you're also using the right tool in your toolbox.

play02:06

That's what this talk is about.

play02:07

Developers like you have a large influence

play02:10

on how successful the device is at managing energy consumption.

play02:14

Let's dive into how to do that.

play02:16

When starting out on your journey

play02:18

to improve your app's battery efficiency,

play02:21

the first question to ask yourself

play02:23

is, have I selected the right tool,

play02:26

the most optimal API for my feature

play02:28

to run in the background?

play02:30

The APIs available for doing work

play02:32

once the app is no longer visible

play02:34

can be split into the following four categories--

play02:37

one, using only asynchronous APIs along

play02:41

with lifecycle-aware components; two, optimized scheduling APIs;

play02:46

three, use-case-specific APIs; and lastly, for scenarios

play02:51

to continue a user action, as the name suggests,

play02:54

Foreground Service.

play02:55

Here's a flow chart to ask yourself to understand which

play02:59

category you should be using.

play03:01

Does the device need to continue once the app has

play03:04

been backgrounded?

play03:06

For example, if you start fetching a news

play03:08

feed for your app, finishing this work after the user

play03:12

leaves the app does not provide user value.

play03:15

You should use asynchronous APIs along

play03:17

with lifecycle-aware components to cancel the work

play03:20

once the user leaves the app.

play03:22

Is the user aware of this background task?

play03:25

If this is a user initiating the action

play03:28

or it requires immediate user feedback,

play03:30

Foreground Services may be appropriate.

play03:33

For example, if a user is playing music and wants

play03:36

the music to continue playing once the app is

play03:39

in the background, you can use a Foreground Service with the type

play03:42

''media playback''.

play03:43

For short critical tasks, such as completing a payment,

play03:47

you can use the Foreground Service with the type

play03:49

''short service.''

play03:50

If the user is not aware of the work

play03:53

or does not require feedback, you

play03:55

should instead leverage optimized scheduling APIs.

play03:59

For example, doing a periodic backup of local content

play04:02

to the server does not require user awareness.

play04:06

These are great ways to optimize app battery that

play04:09

also enhance user experience.

play04:11

Before deciding on using a Foreground Service,

play04:14

is there an alternative API for your use case?

play04:18

You can find in our Foreground Service type documentation

play04:21

alternative APIs that help you manage the runtime lifecycle

play04:25

or trigger the work in more battery optimal ways.

play04:28

The alternative APIs also provide

play04:31

use-case-specific benefits.

play04:33

The most common scenarios for using alternative APIs

play04:37

are, using user-initiated data transfers to do large downloads

play04:41

or uploads, instead of creating a data-sync Foreground Service.

play04:45

This API has the ability to retry

play04:47

if the transfers fail and will execute only

play04:50

during network availability.

play04:52

Also, using companion device manager for Bluetooth pairing

play04:56

and data transfer, instead of using

play04:58

connected-device foreground service.

play05:00

Deciding the right tool is step 1 of the journey

play05:03

to improve battery efficiency.

play05:05

Step 2 is making sure that you're also

play05:07

using the tool correctly.

play05:09

Let's cover best practices of two of the most common options.

play05:13

Using optimized scheduling APIs and using Foreground Service.

play05:18

Here are three best practices when

play05:20

using optimized scheduling APIs that improve battery efficiency.

play05:24

These tips apply for both WorkManager and JobScheduler.

play05:28

When you go to sleep for the night,

play05:30

would you rather be woken up 16 times, every 30 minutes,

play05:34

or would you rather be woken up once

play05:36

and get everything done all at once?

play05:39

The device is similar to the user, the more

play05:42

times the device is woken up, the more energy is consumed.

play05:46

You should declare a constraints to ensure that the task runs

play05:49

in more optimal scenarios and when possible,

play05:52

batch the work together.

play05:53

Setting constraints, for example, executing

play05:56

while charging or executing on an unmetered network,

play06:00

help ensure that the task executes

play06:02

during less-expensive windows of time.

play06:05

The charging constraint is especially recommended

play06:08

on wear devices to minimize battery drain.

play06:11

By default, the system chooses when

play06:13

to run your task when it is most efficient.

play06:16

It may not run immediately when you schedule the task

play06:19

and the app is not in a visible state.

play06:21

You can exempt this optimization by using the expedited flag.

play06:26

However, you should only do so if the task is time sensitive.

play06:30

There are quotas on how much runtime expedited tasks can

play06:34

run for since expedited tasks drain more energy

play06:37

than the default running task.

play06:39

A valid scenario where you can use the set expedited flag

play06:43

is for a task that should happen as a result

play06:46

of a high-priority FCM.

play06:48

An invalid scenario is to override system optimizations.

play06:52

The default task will execute at a system

play06:55

optimal time once the define constraints are met.

play06:59

Use the getStopReason method to find out

play07:01

how your task was stopped.

play07:03

For example, if your task often gets the stop_reason_timeout,

play07:08

there could be an edge case that should be canceled

play07:10

and requires further debugging.

play07:12

We encourage you to track this data via your analytics engine

play07:16

to help you detect how often your task is

play07:19

stopped by the system.

play07:20

Furthermore, if your task times out too often,

play07:23

the system can put your application

play07:25

into a restricted state.

play07:27

Here are three best practices when

play07:30

using Foreground Services that improve battery efficiency.

play07:33

Avoid using wakelocks unnecessarily, especially

play07:37

from a Foreground Service.

play07:39

Wakelocks are a way to prevent the CPU from sleeping

play07:42

when the screen is off.

play07:43

However, they can be tricky to manage

play07:45

and can waste battery when managed inefficiently.

play07:49

Here are some questions to consider when using a wakelock.

play07:52

Are you already using an API that

play07:55

is an alternative to holding a wakelock?

play07:57

For example, if you're using WorkManager, JobScheduler

play08:01

or ExoPlayer, you do not need to acquire a wakelock.

play08:04

Does the use case require the device

play08:07

to perform even when the screen is off?

play08:10

If you only need to do something periodically

play08:12

and while the device is awake, a wakelock

play08:15

is not necessary, for example, if you're using a Foreground

play08:19

Service to intermittently communicate

play08:21

with an external device and there

play08:23

is no user value to this communication

play08:25

while the screen is off.

play08:27

Foreground Services should only be

play08:28

used for the duration of the user action.

play08:31

Once the action is paused or completed,

play08:34

you should stop the Foreground Service.

play08:36

Running the service for longer than the user action

play08:39

can allow for other unrelated asynchronous

play08:41

work to keep running and unexpectedly consume battery.

play08:45

For example, if you're running a Media Playback Foreground

play08:49

Service for playing music in the background,

play08:52

once the user has paused the music,

play08:54

you should immediately stop the Foreground Service.

play08:57

You can verify that the Foreground Service has

play09:00

been stopped in the Task Manager available on devices running

play09:03

Android 13 and higher.

play09:06

Foreground Services are intended to continue

play09:08

a user-initiated action.

play09:10

Are you leveraging a background exemption

play09:12

to start the service when the app isn't visible?

play09:16

For example, you may be using BOOT_COMPLETED broadcast

play09:19

receiver exemption to start a Foreground Service immediately

play09:23

after the device has restarted.

play09:25

We strongly recommend waiting until the user has indicated

play09:28

intention to restart the action to use this Foreground

play09:32

Service again.

play09:33

We are also adding restrictions to which Foreground Services can

play09:36

start from BOOT_COMPLETED when targeting Android 15.

play09:40

If you're interested in learning more

play09:42

about best practices for either optimized scheduling

play09:45

APIs or Foreground Service, you can

play09:47

consult our developer documentation linked

play09:50

in the video description.

play09:51

Now I'll hand it over to my colleague Philip to share tips

play09:55

on how to improve battery efficiency using Perfetto.

play10:00

PHILIP CUADRA: Hi.

play10:01

I'm Philip Cuadra from the Android Software Performance

play10:04

team.

play10:05

We're at the final step of our journey

play10:07

to bettering battery efficiency, inspecting our handiwork.

play10:12

If you want to level up further, you can use the performance

play10:15

inspection tool Perfetto and an Android 14+ device that supports

play10:20

On Device Power Monitoring, such as Pixel 6 and subsequent Pixel

play10:25

devices to manually analyze power and network usage.

play10:30

First, let's go through the setup instructions.

play10:33

There are multiple methods of getting the system trace.

play10:37

We recommend manually capturing a trace

play10:40

through Perfetto using the custom record settings.

play10:43

First, go to ui.perfetto.dev.

play10:46

It will look something like this.

play10:49

Go to ''Record a new trace'' to get started.

play10:52

You will need to make some changes for the recording

play10:55

configuration.

play10:56

Set the max duration to support the full duration

play11:00

of testing your feature.

play11:02

We have it set to five minutes for this demo.

play11:05

In power probe, on the side menu,

play11:08

turn on "Battery drain & power rails."

play11:11

Go to "Android apps and services'' probe and turn

play11:15

on "Atrace userspace annotations."

play11:17

We've selected ''activity manager," ''audio," "network"

play11:22

and "power management" annotations.

play11:24

Scroll down to turn on "Network Tracing" in the Perfetto UI.

play11:29

This is a feature that is launching on ODPM-compatible

play11:33

Android 14 devices.

play11:36

PHILIP CUADRA: You can start recording the trace

play11:38

once you've connected your ADB device.

play11:41

There is a lot to learn about Perfetto

play11:43

that we won't be able to cover as a part of this talk.

play11:47

If you're keen to learn more, watch the Performance Debugging

play11:51

MAD skills series on YouTube.

play11:54

For this talk, we'll profile a media player

play11:57

that continues to play audio even

play11:59

if the user backgrounds the application

play12:02

or turns the screen off.

play12:04

In this flow, I'll start playing music,

play12:07

switch to a different app, and eventually pause the music

play12:11

and turn off the device screen.

play12:14

However, there are a few hard-to-detect bugs

play12:17

that are resulting in poor battery efficiency.

play12:20

Now that we've profiled the major flows of our app,

play12:24

let's stop the trace and inspect the results.

play12:27

Once you've opened the trace, it will look something like this.

play12:32

We're going to focus on a few attributes

play12:34

to inspect as part of this trace.

play12:37

Use the pen icon by hovering over the corresponding track

play12:41

to pin the important attributes to the top of our trace.

play12:46

I've gone ahead and pinned some key info.

play12:49

You can pause the video now to search and find

play12:52

the same attributes and pin it to your Perfetto trace.

play12:56

Let's break down these key attributes.

play13:00

The screen state indicates whether or not

play13:02

the screen is on or off.

play13:04

In our trace, the device's screen eventually turns off.

play13:09

The top app indicates, what is the visible app

play13:12

the user currently has on the device?

play13:15

The device Suspend or Resume indicates

play13:18

if the device is in suspend mode, which

play13:20

helps conserve battery.

play13:23

Note that the device seems to never go

play13:26

into suspend mode on our device.

play13:28

Here's where things get interesting.

play13:30

We are able to use battery_stats.audio to help us

play13:34

understand when the audio track is being utilized.

play13:38

We can see that despite our expectations,

play13:41

the foreground app shows that our declared

play13:44

Foreground Service continues to run even after the music has

play13:48

stopped playing.

play13:50

Also, in Device State--

play13:51

Long wakelock, we can see that there

play13:54

are two wakelocks being held--

play13:56

audio mix and the media wakelock,

play13:58

which continues to run even after the audio

play14:01

is no longer playing.

play14:03

There is also repeating network requests

play14:06

coming from the app denoted in the light-green indicators that

play14:09

happen about every 20 seconds, even after the audio is

play14:13

no longer streaming.

play14:15

This request is not related to media playback,

play14:18

so it shouldn't be happening once the app is

play14:20

no longer visible.

play14:23

You can click on each network indicator

play14:25

to better understand where the request came from.

play14:29

The indicators of different colors

play14:31

are coming from other applications.

play14:34

If you take a look at the modem power track,

play14:36

you will notice a corresponding bump in power usage.

play14:40

Remember this chart?

play14:42

Earlier in the talk, Alice mentioned

play14:45

that cellular modem, which corresponds to the modem power

play14:48

track, is the device component that drains

play14:51

the most amount of power.

play14:53

If I had followed best practices,

play14:56

I wouldn't have encountered these issues.

play14:59

Pause this video if you want to take a moment

play15:02

to think about which best practices apply

play15:04

to this scenario.

play15:06

Number one, we're manually acquiring a wakelock

play15:10

and failing to release it once the media stops playing.

play15:14

As seen in long wakelocks, ExoPlayer library

play15:18

was already holding a wakelock on our behalf.

play15:21

It is unnecessary in this scenario

play15:24

to manually acquire a wakelock.

play15:27

Number 2, the Foreground Service continues

play15:30

to run even after the media is stopped.

play15:33

The Foreground Service should be stopped as soon

play15:36

as the media stops playing.

play15:38

Number 3, the 20-second recurring network activity is

play15:42

tied to the application scope, instead of the view or activity

play15:46

scope, which causes the network request to keep happening even

play15:50

when the app is no longer visible.

play15:53

This is why it's so important to ensure

play15:56

your network requests are tied to lifecycle-aware components.

play16:01

Here is another trace now that we've fixed the issues.

play16:05

Notice how the device is able to go into suspended mode,

play16:08

indicated by the suspend resume track.

play16:11

Also, the wakelock and foreground app duration

play16:14

are much shorter, running only for the duration of the media

play16:18

session.

play16:19

We also don't see any additional network

play16:22

requests coming from the app once the app is not

play16:25

playing media.

play16:26

When looking at the modem power track,

play16:28

we no longer see the corresponding power-drain bump.

play16:32

We're continuing to make improvements

play16:34

on tooling so that you can better debug performance,

play16:37

both within Perfetto and in Android Studio.

play16:40

If you're interested in debugging power

play16:43

on Android Studio, check out the I/O talk that Mayank is giving,

play16:47

actionable app profiling in Android Studio.

play16:50

Now, I'll hand it back to Alice to wrap things up.

play16:54

Thanks, Philipp.

play16:55

Wow, that was quite a journey we went on.

play16:58

Let's recap what we learned.

play17:00

We learned about how background work and power consumption

play17:03

are connected.

play17:05

A major contributor to bad battery experiences

play17:07

is actually screen off battery drain.

play17:10

Developers should not solely rely on system optimizations

play17:13

to improve battery life.

play17:15

We learned about how to select the most optimal APIs

play17:19

for running work in the background using this flowchart,

play17:22

as well as best practices using optimized scheduling

play17:25

APIs and Foreground Services.

play17:28

Finally, we upleveled our skills by learning

play17:31

about how to record a system trace and inspect

play17:34

the trace using Perfetto to optimize for network

play17:37

usage and battery drain.

play17:38

Android will continue to optimize and build

play17:41

APIs that encourage developers to shift energy away

play17:44

from invisible use cases and towards customer visible use

play17:48

cases that provide measurable value.

play17:51

Remember Bob?

play17:53

Thanks to all of your efforts, his device

play17:55

is draining far less battery, and he's able to get home.

play17:59

That's all from me.

play18:00

Thanks for watching.

play18:01

[MUSIC PLAYING]

Rate This

5.0 / 5 (0 votes)

Etiquetas Relacionadas
Battery EfficiencyApp DevelopmentBackground WorkPower ConsumptionOptimized APIsForeground ServicesAndroid SystemPerformance ToolsEnergy ManagementUser ExperienceDevice Optimization
¿Necesitas un resumen en inglés?