This article has been published simultaneously to my technical wechat public account. You can follow it by scanning the TWO-DIMENSIONAL code at the bottom of the article or searching “Programmer Station” on wechat, and update high-quality technical articles from time to time. At the same time, welcome to join the QQ technology group (group number: 650306310) to exchange and learn together!

Battery optimization has always been a platitudes topic, there have been a lot of articles about this, recently also doing this thing, so combined with their own understanding to write this article. Ok, to begin our topic today, I will discuss this area according to the following structure.

Whole process analysis of electricity consumption

Mobile devices perform various tasks and complex calculations, such as uploading selfies to moments and livestreams, which can quickly drain the battery. Obviously, the more complex the task, the faster and faster the battery will run out, and in the blink of an eye, the user’s phone will suddenly become a brick, and the user will suspect who (or which app) is using up the battery and take it off!

The key to writing a low-power application is to thoroughly understand the process.

In the world of electronic programming, the process by which hardware consumes power to perform a task is called timeout current depletion, and as anyone who specializes in electronic programming will tell you, your device’s various activities consume different amounts of power over the same period of time.

For example, many cell phones claim to be on standby for several days, which is true, but if you use airplane mode and do nothing at home, you can indeed last for more than 10 days. But as soon as we use it, such as using cellular wireless data exchange (3G4G) and keeping the screen awake, the battery drains quickly.

As developers, we want to know which tasks my app performs that consume the most power? This is going to be really tricky. Because the calculation and statistics of electricity consumption is a troublesome and contradictory thing, recording electricity consumption itself is also a matter of electricity consumption (so many devices have eliminated the function of monitoring electricity).

The only practical solution is to use a third-party device that monitors battery life, so that you can get a true picture of battery life (because third-party hardware monitors battery life using your own battery, not your phone’s battery life).

Power consumption, for example: open the screen, all actions to use CPU/GPU work will wake up the screen, will consume power. This is not the same as an application waking up the device. For example, use wake Clock, AlarmManager, JobSchedulerAPI.

What’s the biggest drain on your phone?

Wake up the screen

When the user lights up the screen, it means that the components of the system need to start working and the interface needs to start rendering.

Power consumption in standby state:

After using and waking up the screen:

When the device is awakened from sleep by the application, you can see a peak power usage line on the first awakening.

CPU wake up usage

Peak line when CUP wakes up:

Then there are some subsequent execution costs:

When the work is done, the device actively hibernates, which is important, as keeping the screen awake for long periods of time when it is not in use or is rarely used can quickly drain the battery.

Cellular wireless

When the device is sending data over the wireless network, there is a wake up peak in order to use the hardware. And then there’s a high number, this is the amount of power it takes to send the packet, and then it takes a lot of power to receive the packet and you see a spike.

Typically, when data is transmitted over 3G mobile networks, there are three states of power consumption:

  • Full power: The highest power state in which the mobile network connection is activated, allowing the device to operate at maximum transmission rates.
  • Low Power: An intermediate state that consumes about 50 percent of Full power.
  • Standby: The lowest state. There is no data connection to transfer and the lowest power consumption.

Use of Battery-Historian as an energy analysis tool

To optimize Battery life, we first need to know where electricity is being consumed, which can be analyzed by Google’s open-source Battery-historian.

Open source address: github.com/google/batt…

Install the Battery History tool

According to gitbub, there are two ways to install the Battery History tool:

Method 1: Install the Docker environment. (It’s easy, and Docker really works.)

  1. Follow the instructions on the Docker website to install Docker Community Edition.
  2. Run Battery Historian image using the following command:
Docker --run -p port_number:9999 gcr. IO /android-battery-historian:2.1 --port 9999Copy the code

Method 2: install by compiling the source code above gitbub.

  1. GO environment installation: concrete can refer to the Mac OS installation golang development environment (www.jianshu.com/p/79bdd20c4)…
  2. Install git.
  3. To install Python. Python2.7 is supported only (www.python.org/)
  4. Installing the Java Environment

Download the Battery Historian source code and run it

Enter the following command line to download the GOPATH configuration directory.

go get -d -u github.com/google/battery-historian/...
Copy the code

Into the $GOPATH/src/github.com/google/battery-historian directories below

cd $GOPATH/src/github.com/google/battery-historian
Copy the code

1. Run Battery Historian

go run setup.go
Copy the code

Compile Javascript files using the Closure compiler


go run cmd/battery-historian/battery-historian.go [--port <default:9999>]
Copy the code

Run Historian on your machine (make sure GOBIN) 3. Check the web site http://localhost:9999 to see if battery-historian is running.

Here Battery-historian can save the world.

Electric quantity data collection

Android 5.0 and above devices allow us to dump power usage statistics using ADB commands. 1. Since the battery statistics are continuous and will be very large, the statistics of the App to be tested need to be connected to the device, so the battery data collection needs to be reset. Command line execution:

$ adb shell dumpsys batterystats --resetBattery stats reset
Copy the code

2. Disconnect the test device from the USB connection and operate the App to be tested.

3. Reconnect the device and run adb to export related statistics:

  • Android 7.0 or later run the following command:
adb bugreport > [path/]bugreport.zip
Copy the code
  • Android 5.0/6.0 Run the following command:
adb bugreport > [path/]bugreport.txt
Copy the code

The exported statistics are stored in bugreport.zip(bugreport.txt) and can be graphically displayed as battery consumption by battery-historian.

Upload the bugreport.zip(bugreport.txt) file to http://localhost:9999:

Battery -historian Analysis results:

Analysis indicators

Below is an analysis of the Battery data collected by uploading it to Battery Historian using adb command. (We can filter the power consumption of specific applications by packet name)

The meanings of indicators

  • Horizontal coordinate: The horizontal coordinate is a time range. In our example, the statistical data starts from reset and ends when the bugreport content is obtained. How long we collected data;
  • Ordinate: The key data points are described as follows.
A data item instructions
battery_level Quantity of electricity, you can see the change in quantity of electricity
plugged Charging status, this column shows whether charging has been carried out, and the time range of charging
screen Whether the screen is lit up or not can take into account information about sleep state and power usage in the lit state
top This column displays which app is at the top at the current moment, which is the app currently running on the mobile phone. It is used to judge the influence of an app on the mobile phone power, and thus can also judge the power consumption information of the app. This column records when an application was started and how long it was running, which is a great help in comparing the performance impact of different applications
wake_lock Wake_lock This property records the working time of the wake_lock module. Whether there is a time to stop etc
running Check whether the interface is in idle state. It is used to judge the power consumption under no operation state
Job Background work, such as running the service Service
data_conn The change of data connection mode, the edge above is to illustrate the use of GPRS to connect the network. The data shows whether the phone is using 2G, 3G, 4G or wifi for data exchange. This column shows the influence of different connection modes on power consumption
status Battery status information, including charging, discharging, uncharged, full, unknown and other different states
phone_signal_strength Changes in cell phone signal status. This column records the strength and weakness of mobile phone signals to judge the influence of mobile phone signals on electricity in turn
health Information about the health of the battery, which in part reflects how long the battery has been used
plug Charging method, USB or socket, and display time of connection
Sync Whether to synchronize with the background
phone_in_call Whether to make a Call
gps Whether GPS is on

How to optimize power quantity?

Understand the key power consumption areas of mobile phones and analyze power consumption tools. Then comes our core, how to optimize the quantity of electricity? First of all, we simply summarize the relevant factors of electricity consumption

  • Screen light and dark are correlated
  • Device awake,sleep switch, especially wake up.
  • CPU runtime correlation
  • network
  • The sensor

We all know that screen rendering and CPU running is a major power drain. So when we’re doing memory optimization, rendering optimization, computing optimization, we’re already doing battery optimization. Therefore, in the usual development, we should pay attention to the optimization and accumulation of bit performance. In fact, when we do electricity analysis, we are also looking for their own pits. Therefore, we should try to consciously dig as few holes as possible in the process of project development, which is the first point we should mention when analyzing other optimization items.

Monitor cell phone charging status

We can obtain the current charging status of the phone by using the following code:





Here we need to think, according to the specific business, consider some of the operations that do not need to interact with the user in time to do when charging. For example, when the 360 mobile phone assistant is charged, it will automatically clean up the mobile phone garbage, automatically back up and upload pictures and contacts to the cloud, so as to avoid the power consumption operation when the user’s mobile phone is low.

Wake up the screen

When the Android device is idle, the screen darkens, turns off the screen, and finally stops the CPU to prevent the battery from draining too quickly. But there are times when we need to change the Android system’s default state: for example, we need to keep the screen on while playing a game, for example, some downloads do not require the screen to be on but require the CPU to run until the task is complete.

A good way to keep the screen on is to use the FLAG_KEEP_SCREEN_ON Flag in your Activity.

The advantage of this approach is that unlike wake locks, there are no specific permissions required. And can correctly manage the switch between different apps, do not worry about the release of useless resources.

Another way is to use the Android :keepScreenOn property in the layout file:

Android :keepScreenOn = “true” works the same as FLAG_KEEP_SCREEN_ON. The nice thing about using this code is that you allow you to close the screen where you need to.

Note: There is no need to manually remove the FLAG_KEEP_SCREEN_ON flag, windowManager will manage the application into the background and back into the foreground. If you really need to manually clear the flag that is on, run the

Therefore, we need to control whether to keep the screen constant according to the actual situation of our APP and business. For example, the APP needs to support video playback. So in the play interface need to control the screen, when exiting play, of course, there is no such setting.

WakeLock

The wake_lock lock is related to the sleep of the system, which means that the system will not sleep when the program puts this lock on the CPU. The purpose of this lock is to fully cooperate with the operation of our program. In some cases there are problems if you don’t do this. You need to use the Wake locks feature of the PowerManager system service to keep the CPU in the wake state. Wakeup locks allow applications to control the power status of the host device. Creating and holding a wakeup lock has a significant impact on battery life, so use it only when you really need it to complete a task that can be done in the background in the shortest possible time. For example in the Acitivity you don’t have to use it. If you need to turn off the screen, use FLAG_KEEP_SCREEN_ON above.

There is only one reasonable usage scenario where a background service is used to hold the CPU to do some work with the screen off, and a wakelock is required. If you do not use a wakelock to perform the background service, there is no guarantee that the task will stop at some point in the future due to CPU sleep, which is not what we want.

Wakeup locks can be divided and identified as four types of user wakeup locks:

Tag values CPU The screen The keyboard
PARTIAL_WAKE_LOCK open Shut down Shut down
SCREEN_DIM_WAKE_LOCK open dim Shut down
SCREEN_BRIGHT_WAKE_LOCK open brighten Shut down
FULL_WAKE_LOCK open brighten brighten

Note: starting with API level 17, FULL_WAKE_LOCK is deprecated. The application should use FLAG_KEEP_SCREEN_ON.

1. Add wake lock permission:

2. Use wake lock directly:

Note: When using this class, acquire and release must be paired. Otherwise, when our business is no longer needed, when the CPU is in the wake state, this time will consume the excess power.

JobScheduler

Since The release of Android 5.0, JobScheduler has become a great way to perform background work in a way that allows users to do the right thing at the right time. Applications can schedule jobs while allowing the system to be optimized based on memory, power, and connectivity. The purpose of JobSchedule is to batch less urgent tasks at a more appropriate time. This has two advantages:

  • Avoid frequent awakenings of hardware modules, resulting in unnecessary power consumption.
  • Avoid performing too many tasks at inappropriate times (such as low battery conditions, weak network or mobile network) and consuming too much power.

GPS

Select the appropriate Location Provider

Android system supports multiple Location Providers:

  • GPS_PROVIDER: GPS positioning, using GPS chips to obtain their own position information through satellites. High positioning accuracy, generally about 10 meters, large power consumption; But inside, GPS is of little use.
  • NETWORK_PROVIDER: Uses the addresses of cell phone base stations and WIFI nodes to roughly locate the location. This location method depends on the server, that is, the ability of the server to translate the information of the base station or WIF node into location information.
  • PASSIVE_PROVIDER: PASSIVE_PROVIDER is used for passive positioning. When other applications update positioning information using positioning, the system will save the information and the application can read the information directly after receiving the message.

If the App only needs a rough location, there is no need to use GPS for location, which consumes power and takes a long time to locate.

Deregister location listening in time

After obtaining the positioning or when the program is in the background, log off the positioning monitoring. At this time, monitoring the GPS sensor is equivalent to executing no-OP (no operation command), which will not be perceived by the user but consumes power.

Multi – module use location as far as possible complex

Multiple modules use positioning, try to reuse the last result, rather than all re-positioning process, save power loss; For example: get the location once when the application starts, save the result, and fetch the location directly after it is used.

The sensor

Use the sensor to select the appropriate sampling rate, the higher the sampling rate type, the more power consumption.

  • SENSOR_DELAY_NOMAL (200000 microseconds)
  • SENSOR_DELAY_UI (60000 microseconds)
  • SENSOR_DELAY_GAME (20000 microseconds)
  • SENSOR_DELAY_FASTEST (0 microseconds)

In the background, pay attention to timely logout sensor listening

Doze and App Standby

Finally, this point is theoretically not power optimization, but to do power optimization to pay attention to a pit. Doze and App Standby is Android 6.0 onwards and offers two features to save power and extend battery life. For details, please refer to Google’s official introduction documentation.

Reference: github.com/google/batt…

Follow the technical public account “Programmer Station”, search “programmer Station” on wechat, or scan the qr code below on wechat to follow: