Performance optimization series

APP startup optimization

UI rendering optimization

Memory optimization

Image compression

Long figure optimization

Power optimization

Dex encryption

Dynamic replacement Application

Exploring the principle of hot fix for APP stability

APP continuous running process alive implementation

ProGuard compresses code and resources

APK limit compression

Electricity optimization – battery-historian

Introduction to the

Nowadays, almost everyone has a smart phone. You can find that no matter walking on the street, on the bus or subway, or in any entertainment office, you can see people playing with their mobile phones with their heads down, and some of them even carry a charging bank with them. It can be seen that how unused the battery of smart phones is now, of course, we can not optimize the battery, but we can start to optimize from the APP, I believe that the first-line manufacturers also have their own power analysis tools, I believe that as long as the tools can analyze the power, are good tools (^▽^). So it’s time for us to take a look at BatteryHistonian using Google’s battery-historian tool.

Battery-Historian

‘Historian background

Battery Historian is a tool to check Battery related information and events on Android devices running Android 5.0 Lollipop (API level 21) and higher without the device being plugged in. It allows application developers to visualize system and application-level events on a timeline with pan and zoom features that make it easy to view various summary statistics since the device was last fully charged, select an application and examine metrics that affect the selected application’s specific battery. It also allows A/B comparison of two error reports, highlighting differences in key battery-related metrics

‘Historian installation

The installation of Battery Historian is a complex project that requires a large array of installations. But the official provided us with 2 in the installation, let’s understand the next.

Quick install – Baidu Cloud

‘historian source and JS environment: pan.baidu.com/s/1D3Guq0WW… Extract code: G1CX

Usage:

  1. Decompress it in the $GOPATH/ directory of GO and GO to step 5.2 -> 5.4
  2. For Internet Explorer or Google, enter http://localhost:9999/
Source code installation (recommended)

Source installation although the configuration of a lot of environment, but it is still relatively stable to use, with my pace to install it together.

  1. Install and configure the GO language

    1. Science download online or use the extract code I downloaded: NH8P

    2. Installation Attention Change path

    3. Configure the environment

      Create the GOROOT GOPATH variable in the system variable and configure the Path environment variable

    4. Check whether the installation is successful

      On the COMMAND-LINE interface (CLI), enter go version to check whether the installation is successful and the current version is displayed

  2. Python installation

    Since the script is written in python2, the python2.7 environment needs to be installed.

    Download and install: www.python.org/

    The cloud disk to install: pan.baidu.com/s/103GXARgc… Extract code: SM8P

    1. Download version 2.7 from the official website

    2. Install the py

    3. Configure the environment

    4. To verify the root permission, enter python -v

      If the version number is displayed, the installation is successful

  3. Configuring the JAVA Environment

    This is his Baidu configuration ha.

  4. Configuring the Git Environment

    This also oneself Baidu bar, very simple.

  5. Download the source code of Battery Historian

    1. In the Git Bash input command go get – d – u github.com/google/battery-historian/… (that is, download to the GOPATH configuration directory)

    2. Into the $GOPATH/src/github.com/google/battery-historian directory

    3. Run Battery Historian: Enter the go run setup.go command line

    4. Run ‘Historian. Go

      Go run CMD /battery-historian/battery-historian. Go under battery-historian

    5. Browser input

      http://localhost:9999

MAC source installation (recommended)

The installation procedure is the same as that for WIN. The following instructions directly describe the environmental requirements for Battery historian under MAC

  1. Go Environment Configuration

    1. Vim. brash_profile Configures the GO environment

    2. Save the edit environment

      sorce .brash_profile
      Copy the code
Docker installation

Docker I here roughly said, because in Win10 under the installation pit too much. It is also a bit unstable, resulting in the final source installation.

The preparatory work

The official website to download Docker: docs.docker.com/engine/inst…

Win 10 Home edition is missing hyper-V component, you need to upgrade enterprise edition password key can also be: NPPR9-FWDCX-D2C8J-H872K-2YT43

  1. Install The Docker for Windows Installer. Go to the next step. During the installation process, the computer will automatically restart.

  2. Enter the command to run Docker

    docker run --name=battery -d -p 9999:9999 bhaavan/battery-historian
    Copy the code

  3. Verify: Type http://localhost:9999 in your browser

Note:

  1. If win10 enterprise edition installation failed, you can see the official website prompt

  2. If you upgrade the enterprise version and VMware virtual machine is not available, here is the solution.

    1. None Example Close the Hyper-V component

      bcdedit /set hypervisorlaunchtype off
      Copy the code
    2. open

      bcdedit /set hypervisorlaunchtype auto
      Copy the code

Battery Historian use and data analysis

Adb operations for mobile phones
  1. Resetting internal data is equivalent to clearing

    adb shell dumpsys batterystats --reset
    Copy the code
  2. Obtain complete wakelock information

    adb shell dumpsys batterystats --enable full-wake-history
    Copy the code
  3. Unplug the USB and wait for a long time. It is recommended to use the APP at will now

  4. Get power report

    / / > 6.0
    adb bugreport bugreport.zip
    / / < = 6.0
    adb bugreport > bugreport.txt
    / / export
     adb pull /data/user_de/0/ com. Android. The shell/files/bugreports/report [electricity]. Zip [export directory]Copy the code
  5. Submit a battery report and review it

Data parameter description
  1. WakeLock level

    • PARTIAL_WAKE_LOCK: Ensures that the CPU is running at high performance with the screen and keyboard backlight (or perhaps touch button backlight) off. This WakeLock is usually used.

    • ACQUIRE_CAUSES_WAKEUP: This WakeLock causes the screen to light up even when the screen was closed in addition to making the CPU run at high performance.

    • ON_AFTER_RELEASE: If the screen is lit when WakeLock is released, leave the screen lit for a little while after WakeLock is released. If the screen itself is not lit when WakeLock is released, there will be no action.

    • API17 Deprecated WakeLock: Keep the screen bright

      • SCREEN_DIM_WAKE_LOCK: Ensure that the screen is lit, but the brightness may be low. At the same time, the keyboard backlight can also not be bright. SCREEN_BRIGHT_WAKE_LOCK: Ensure that the screen is fully lit and the keyboard backlight is on. FULL_WAKE_LOCK: The performance is similar to SCREEN_BRIGHT_WAKE_LOCK, except that this level of WakeLock uses the highest brightnessCopy the code
    • It is recommended to use

      • // In the Activity:
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        
        // Or add this property to the layout:
        android:keepScreenOn="true"
        Copy the code

    The remaining parameters are described in the table

    parameter instructions
    CPU runing The running status of the CPU, whether it has been awakened
    Kernel only uptime Only kernel running time
    Activity Manager Proc Active user process
    Mobile network type Network type
    Mobile radio active Mobile cellular signals consume more power than wifi
    Crashes(logcat) Crashes occurred at some point in time (logcat)
    Doze Whether to enter doze mode
    JobScheduler Asynchronous job scheduling, deferred operation, parent class Service
    SyncManager Synchronous operation
    Temp White List Power optimization whitelist
    Phone call Call or not
    GPS Whether to use GPS
    Network connectivity Network connection status (whether wifi or mobile is connected)
    Mobile signal strength Mobile signal strength (great\good\ Moderate \poor)
    Wifi scan Whether wifi signals are being scanned
    Wifi supplicant Whether there is a wifi request
    Wifi radio Whether data is being transmitted over wifi
    Wifi running Whether the wifi component is working (no data is transmitted)
    Wifi on Whether the wifi component is working (no data is transmitted)
    Audio Whether audio is enabled
    Camera Whether the camera is working
    Video Whether the video is playing
    Foreground process Foreground process
    Package install Whether package installation is in progress
    Package active Package management at work
    Battery level Current battery
    Temperature Battery temperature
    Logcat misc Whether logs are being exported
    Plugged Charging state
The current APP Stats

Analyze the detailed information of the current APP battery
  1. As you can see from the chart above, the time between 11:00am and 12:00pm is the time when power drops the most, and GPS and Wakelock are the biggest culprits
  2. In APP Stats -> Device Estimated Power, you can check the power consumption in this hour. (According to the Battery Level in the figure above, the power change process is 69-61. 8) The power consumption of APP in 1H is 5.38%, which is still very power consumption.

Current APP optimization suggestions:

GPS: GPS can be accessed intermittently, or use a third party (Autonavi, Baidu) which provides power-saving positioning mode. If there is wifi, switch to wifi positioning mode, and use less high-precision positioning mode.

Network connection: It is recommended to switch wifi where there is wifi

Wakelock: Try not to use it.

Summary – Optimization scheme

1. Added to the power optimization whitelist

/** * Add power to whitelist **@param activity
     * @paramType 1: start setup page 2: trigger system dialog box */
    public static void addWhite(Activity activity, int type) {
        if (activity == null)return;
        WeakReference<Activity> activityWeakReference = new WeakReference<Activity>(activity);
        PowerManager packageManager = (PowerManager) activityWeakReference.get().getApplication()
                .getSystemService(Context.POWER_SERVICE);
        // Whether the application is in the whitelist
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(! packageManager.isIgnoringBatteryOptimizations(activityWeakReference.get().getApplication().getPackageName())) {if (type == 1) {
                    ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS Intent
                    Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
                    activityWeakReference.get().getApplication().startActivity(intent);
                } else {
                    // Method 2, trigger the system dialog box
                    Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(Uri.parse("package:"+ activityWeakReference.get().getApplication().getPackageName())); activityWeakReference.get().getApplication().startActivity(intent); }}}}Copy the code
2. GPS optimization suggestions

Positioning is a common function in apps, but positioning cannot be uniform. Different scenarios and different types of apps need more personalized differentiation of positioning.

  • Selecting an appropriate Location Provider The Android system supports multiple Location providers:

    GPS_PROVIDER: GPS positioning, which uses GPS chips to obtain its own position information through satellites. High positioning accuracy, generally about 10 meters, large power consumption; But inside, GPS is of little use.

    NETWORK_PROVIDER: Network location, which uses the addresses of cell phone base stations and WIFI nodes to roughly locate the location. This location depends on the server, that is, the ability of the server to translate the base station or WIFI node information into location information.

    PASSIVE_PROVIDER: Passive location, which is an off-the-shelf location. When another application updates the location with the location information, the system saves it and the application reads the message directly after receiving it. For example, if the system has been installed Baidu Map, Amap (indoor can achieve accurate positioning), as long as you use them after positioning, and then use this method in your program is sure to be able to get more accurate positioning information.

    Use Criteria to set the appropriate requirements such as mode, power consumption, altitude and speed, and the system will return the appropriate Location Provider. For example, if your App only needs a rough location, then you don’t need to use GPS for location, which consumes power and takes a long time to locate.

  • Log out of location listening in time After the location is obtained or the program is in the background, log out of location listening. At this time, listening to the GPS sensor is equivalent to performing no-op (no operation instruction). The user will not feel it but it consumes power.

    // If the positioning requirements are not so strict, you can pause when the screen is closed
    public void onPause(a) {
         super.onPause();
         if(locationManager ! =null)
             locationManager.removeListener()
     }
    
    Copy the code
  • Multi-module use positioning as far as possible to reuse multiple modules use positioning, as far as possible to reuse the last result, rather than all re-positioning process, save power loss; For example, get a location when the application starts, save the results, and then use the location directly.

3. Network switch It is recommended to use WIFI for uploading and downloading
// Optimization solution 2: network data switchover
        if(! BatteryUtils.isPlugged(getApplicationContext())){// If there is no charging, remind the user whether wifi is available
        }
Copy the code
4. WakeLock is on screen to wake up the CPU
  1. Bright screen replacement

    // In the Activity:
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    
    // Add this property to the layout:
    android:keepScreenOn="true"
    Copy the code
  2. Alarm causes the CPU to work intermittently

        /** * Turn on an alarm clock *@param context
         * @param action
         * @param requestId
         * @param interval
         */
        public static void startTimer(Context context,String action,int requestId,int interval) {
            Intent intent = new Intent(action);
            PendingIntent sender = PendingIntent.getBroadcast(context, requestId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    
            Calendar calendar = Calendar.getInstance();
            int second = calendar.get(Calendar.SECOND);
            // Delay execution by one minute
            int delay = 60 - second + 1;
            calendar.add(Calendar.SECOND, delay);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                String format = new SimpleDateFormat("HH:mm:ss", Locale.CHINA).format(calendar.getTimeInMillis());
                Log.d("Time for the next alarm --"."delay: " + delay +", startMillis: " +format);
                alarmManager.setWindow(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 100, sender);
    
            } else{ alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval, sender); }}Copy the code
5. JobScheduler (Service replacement) After 8.0 Google recommended use)
  1. Save your tasks for the right time of day, such as charging time and after wifi connection

  2. You can also combine multiple tasks and perform them at a selected time

    @override public int enqueue(JobInfo job) @override public int enqueue(JobInfo job) @override public int enqueue(JobInfo job, JobWorkItem work) { try {return mBinder.enqueue(job, work);
            } catch (RemoteException e) {
                returnJobScheduler.RESULT_FAILURE; } // Override public List<JobInfo>getAllPendingJobs() {
            try {
                return mBinder.getAllPendingJobs();
            } catch (RemoteException e) {
                returnnull; }}Copy the code

    In case the execution of this jobSchedler merge task isn’t clear, let’s look at the next screen (5.3)

  3. Send data while charging and connected to wifi (in this case, rotating the screen is used to send data).

    • First, let’s talk about the demonstration process. Data will be sent normally after wifi + charging

    • Turn off wifi to send data, and turn on wifi to merge data

So now we’re pretty much done with power optimization and we’re actually optimizing by 2%. Not bad, either.

Code transfer matrix

conclusion