A lot of students have come to urge me recently. Do you still want to tell me? As Living water transferred to wechat, the seven rounds of interview lasted two months, and the green channel defense lasted almost half a month. I find that many times are involuntarily, not do not want to do but really have no time. We want to do something, but we really don’t have the body and time.

App “Power Consumption Syndrome”

What are we talking about when we say an App consumes power?

We may refer to the App eating the CPU, which causes the system to lose power quickly. We may also refer to the system alarm, App background scanning frequently consumes power, or the phone becomes hot when using the App. Yes, compared with Crash, ANR and other common APM indicators, battery optimization of Android App is more like a comprehensive problem.

On the one hand, there are various reasons for the power consumption of App, such as CPU/GPU Load, screen, sensor and other hardware costs, etc., and the troubleshooting ideas of each category are quite different. Moreover, AOSP has no “official” power consumption abnormal detection framework. The monitoring schemes for App power consumption of each OEM system are different (and there are not sufficient public documents). Therefore, the detection schemes should be based on the actual App project and user feedback, and the specific power consumption type should be considered and selected. On the other hand, the problem of power consumption is often “subjective”. For example, users feel that the new version of THE App has a quick power failure, or the device feels hot when using the App in an outdoor environment with high temperature, or the system ranks higher in power consumption simply because of the longer use time. These are often subtle subjective feelings that are difficult to quantify.

Therefore, how to detect all kinds of abnormal power consumption and how to extract the rules of power consumption problem (red line) are the key to optimize the power consumption index. The wechat Android project has produced some practical tools and optimization ideas in the daily battle with the “difficult and miscellaneous disease” of App power consumption. Aiming at the power consumption problem of Anroid App, this paper mainly talks about “Principle of App power statistics”. Later, we will analyze and share the two parts of “Power consumption Abnormal Monitoring scheme” and related “optimization cases” successively.

Principle of App electricity statistics

Calculation formula of electric quantity

Before understanding the principle of App electricity statistics, it is necessary to review the calculation formula of electricity:

Electric quantity = power x timeCopy the code

One thing to note is that power is equal to voltage times current. In digital products, components are generally sensitive to current, and voltage is basically constant, so we directly use current to replace power, which is why we often say “mAh” rather than “kWh” (kWh).

Battery statistics of Android hardware modules

After understanding the calculation formula, the idea of App’s electricity statistics is relatively clear:

App electric quantity = SUM (module power × module time)Copy the code

Modules mainly refer to various hardware modules of Android devices, which can be divided into the following three categories.

The first kind, like a Camera FlashLight/MediaPlayer/sensors module, such as its basic consistent with rated power, working power so calculation module of electricity only need the use of statistical module length times rated power.

The second type, data modules like Wifi/Mobile/BlueTooth, can be divided into several gears. For example, when the phone’s Wifi signal is weak, the Wifi module must operate at a high power gear to maintain the data link. So the power calculation of such modules is somewhat similar to our daily electricity calculation, which requires “ladder charging”.

The third and most complex type of module, CPU module, in addition to each CPU Core needs to calculate the power like data module, each Cluster of CPU (usually a Cluster contains one or more Core of the same specification) also has additional power consumption. In addition, the entire CPU processor chip also has power consumption. For simple calculation, CPU power = SUM (power consumption of each core) + power consumption of each Cluster + chip power consumption. If we go to the complex direction, CPU power consumption should also consider the power loss of overclocked and the information entropy loss of logic operation (if you are interested in this aspect, you can expand and check by yourself. The CPU power statistics of Android system only calculate the chip power consumption layer). It is more difficult to calculate the power of the screen module, and it is difficult to allocate the screen power reasonably to each App. Therefore, the Android system simply calculates the holding time of the App screen lock (WakeLock), increases the statistic time of the App CPU by a fixed coefficient, and roughly calculates the screen power into the CPU.

Finally, it’s important to note that all of the power and time statistics mentioned above are estimated on Android, which can be quite different from the actual power numbers. Facebook engineers have joked about this: Mistrusting OS Level Battery Levels.

Android system power statistics service

A service called BatteryStatsService provides battery statistics for Android. Let’s take a look at four of the key characters:

  • Power: power_profile. XML. The Android system uses this file to describe the rated power of each hardware module of the device, including the multi-gear power and CPU power values mentioned above.
  • Length: StopWatch & SamplingCounter, wherein StopWatch ⏱ is used to calculate the usage duration of various hardware modules of App. SamplingCounter is used to sample the working time of App on different CPU cores and different CPU freQs.
  • Calculation: PowerCalculators, each hardware module has a corresponding named PowerCalculator implementation, mainly used to complete specific electricity statistics algorithm.
  • Store: batteryStats. bin, a persistent file of data related to the power statistics service.
The working process

The working process of BatteryStatsService can be roughly divided into two parts: duration statistics and power consumption calculation.

BatteryStatsService Duration statistics flow

At the heart of the BatteryStatsService framework is a class called BatteryStats held by TA. BatteryStats also holds an array of Uid []. Each Uid instance actually corresponds to an App. When we install or uninstall the App, BatteryStats updates the Uid element to keep the mapping up to date. BatteryStats also holds a series of StopWatches and SamplingCounters. When the App starts using some hardware module functions, BatteryStats then calls StopWatch or SamplingCounter of the corresponding Uid to count how long its hardware has been used.

Here is an example of the Wifi module: When the App calls the Wifi module through the WifiManager system service to start scanning, Actually by WifiManager# startScan () – > WifiScanningServiceImp – > BatteryStatsService# noteWifiScanStartedFromSource () – > BatteryStats# noteWifiScanStartedLocked (uid) and so on a series of calls, notify the BatteryStats open App uid Wifi module corresponding StopWatch timing starts. When App by WifiManager stop Wifi scanning again through a similar process invokes BatteryStats# noteWifiScanStoppedLocked (uid) over a StopWatch timing, In this way, the statistics of the using time of Wifi module by App can be completed through StopWatch.

BatteryStatsService Power calculation process

Specifically, BatteryStats is calculated using a BatteryStatsHelper helper class that the TA relies on. BatteryStatsHelper uses a combination of the duration data in the Uid, the power data in the PoweProfile (a parse instance of power_profile.xml), and the PowerCalculator algorithm for each module. Calculate the combined power consumption of each App and store the calculated results in the BatterySipper [] array (sorted from highest to lowest by calculated value).

Take the Wifi module as an example: When you need to calculate the App’s power consumption, BatteryStats refreshes the BatterySipper [] array by calling BtteryStatsHelper#refreshStats () –> #processAppUsage () to calculate the latest App power consumption data. The power statistics of Wifi module was completed by WifiPowerCalculator in processAppUsage method: Wifi module power = Idle power preset by PowerProfile x Wifi Idle time collected by Uid + uplink power x uplink time + downlink power x downlink time

public class WifiPowerCalculator extends PowerCalculator { @Override public void calculateApp(BatterySipper app, BatteryStats.Uid u, long rawRealtimeUs, long rawUptimeUs, int statsType) { ... app.wifiPowerMah = ((idleTime * mIdleCurrentMa) + (txTime * mTxCurrentMa) + (rxTime * mRxCurrentMa)) / (1000*60*60); }}Copy the code

Application scenarios

As a supplement, several application scenarios of BatteryStatsService are listed here to illustrate how it works.

Android App power consumption ranking

From the above analysis, we know that the battery consumption ranking of Android App is achieved by reading BatterySipper [] data in BatteryStatsHelper. Typically, BatteryStats is charged with STATS_SINCE_CHARGED since the last time the device was fully charged. However, the details vary from OEM to OEM. Some Android devices can display battery statistics for the last few days or more than a week.

adb dumpsys batterystats & adb bugreport

Perhaps you already know how to Dump your system’s Battery statistics using ADB Dumpsys BatteryStats or ADB Bugreport and how to read them together with Battery Historian, In fact, these ADB commands use BatteryStatsService to query the Uid of BatteryStats [] to obtain the corresponding battery statistics. Specific implementation can reference com. Android. Server. Am. BatteryStatsService# dump.

CPU Load/Usage

For example, CPU Load xx% yy% zz% is a function of ANR, and batteryStats is a function of bugreport. The adb top command displays similar CPU Load data, which is actually calculated by the CPU module count time: CPU Load = SUM (App CPU Core duration)/CPU working time. It should be noted that the CPU duration of App is calculated separately according to CPU Core, so the calculation result may exceed 100%. For example, the theoretical upper limit of the calculation result of an 8-core CPU is 800%.

Later, we will analyze and share the two parts of “Power consumption Abnormal Monitoring scheme” and related “optimization cases” successively. Finally, I want to give you a sentence, which is said in “University” : things have an end and things have a beginning and a end

Video link: pan.baidu.com/s/1GJJCQfL5…

Video password: 3bqh