When talking about the Android performance problems, caton, response speed, ANR the three performance in terms of the relevant knowledge often together, because the cause of caton, slow response, ANR are similar, but according to important degree, artificially divided into caton, slow response, ANR three, so we can define the broad sense of card, There are three types: lag, slow response and ANR. Therefore, if users report that their mobile phones or apps are stuck, most of them are stuck in a broad sense, and it is necessary to figure out which kind of problem has occurred

If it is animation playback lag, list sliding lag, we generally defined as the narrow sense of the lag, the corresponding English description I think should be Jank; Slow response is generally defined as Slow application startup, Slow on-off screen, and Slow scene switching. I think the corresponding English description should be Slow. If ANR occurs, it is an application non-response problem. The analysis methods and solutions corresponding to the three cases are not quite the same, so we need to separate them

In addition, there are separate standards for performance indicators such as lag, response speed and ANR within App or manufacturer, such as frame drop rate, startup speed and ANR rate. Therefore, it is very important for developers to analyze and optimize these performance problems

This article is the third part of the response speed series. It mainly discusses some extended knowledge when using Systrace to analyze application response speed problems, including startup speed test, Log output reading, Systrace state reading, tripartite startup library and so on

If you are not familiar with the basic use of the Systrace(Perfetto) tool, then it is a priority to complete the Systrace basics series. This article assumes that you are already familiar with the use of Systrace(Perfetto)

1. Three states interpretation of the process in Systrace

In Systrace, the most common state of a process task is Sleep, Running, and Runnable. In the process of optimization, these states also need our attention. The process task states are at the top, separated by color:

  1. Green: Running
  2. Blue: a Runnable
  3. White: Sleep

1.1 How to Analyze tasks in Sleep state

There are two kinds of white Sleep, namely active Sleep and passive Sleep

  1. NativePoll generally belongs to active Sleep. Since there is no Message processing, it enters the Sleep state and waits for Message. This is normal and we do not need to pay attention to it. For example, between frames, that’s active sleep
  2. Passive Sleep is usually initiated by the user to invoke Sleep or communicate with other processes using Binder. This is the most common and often encountered when analyzing performance problems, so it needs to be focused on

As shown in the figure below, there is a long sleep during startup. If the Binder communication is frequent during startup, the application waits longer, resulting in a slower response time

This can be done by clicking on binder Transaction at the bottom of the Task to see the binder call information, for example

Sometimes there is no Binder information and it is woken up by another waiting thread. Then you can check the wake up information and find out what the application is waiting for

Zoom in on the Runnable we clicked in the image above

1.2 How to Analyze Tasks in the Running State

Tasks in Running state are those currently Running on a core of CPU. If a task is in Running state and takes a long time, it needs to be analyzed:

  1. Whether or not to apply its own logic time, such as some new code logic
  2. Is running on the corresponding core

On some Android machines, it is common to optimize the scheduling of the main and render threads of the App: the UI Thread and RenderThread of the foreground application usually run on the large core

1.3 How do I Analyze Tasks in the Runnable State

To change a Task from the Sleep state to the Running state, it must first become the Runnable state, as shown in the following figure

The performance on Systrace is as follows

Under normal circumstances, after the application enters the Runnable state, it is immediately scheduled by the scheduler to enter the Running state and start working. However, when the system is busy, the application will spend a lot of time in the Runnable state because the CPU is full and various tasks need to queue up for scheduling

If your application starts up with a large number of Runnable tasks, you need to check the system status

2. Use of TraceView tool in response speed

TraceView refers to the CPU information that is captured in the AS Profiler, AS shown in the screenshot below

2.1 How Do I Capture the TraceView during application startup

To grab the app’s cold start, use the following commands, which can also be executed separately, by switching the package name and Activity name inside to your app’s package name

adb shell am start -n com.aboback.wanandroidjetpack/.splash.SplashActivity --start-profiler /data/local/tmp/traceview.trace --sampling 1 && sleep 10 && adb shell am profile stop com.aboback.wanandroidjetpack && adb pull /data/local/tmp/traceview.trace .
Copy the code

Or execute the above commands separately

// 1. Cold start App, Sampleing = 1 means 1 ms sampling an adb shell am start - n com. Aboback. Wanandroidjetpack /. Splash, SplashActivity - start - profiler /data/local/tmp/traceview.trace --sampling 1 // 2. After waiting for the application in full swing, end profile adb shell am profile stop com. Aboback. Wanandroidjetpack / / 3. Trace files from a mobile phone to pull out inside the adb pull/data/local/TMP/traceview. Trace. / / 4. Use Android Studio to open the traceView.trace fileCopy the code

2.2 What do you think of TraceView

TraceView can be opened directly in Android Studio

The green ones are the ones that apply themselves, and the yellow ones are the ones that apply the system

Application.onCreate

Activity.onCreate

doFrame

The WebView initialization

2.3 Disadvantages of TraceView

Due to the fine sampling, the performance loss is relatively large. Therefore, the captured TraceView, in which the execution time of each method is inaccurate, cannot be used as the real time reference, but can be used to locate the specific function call stack.

It needs to complement Systrace

3. Use of SimplePerf tool in startup speed analysis

Using SimplePerf tools, you can also grab startup stack information, both Java and Native

For instance we should grab com. Aboback. Wanandroidjetpack the cold start of the application, you can perform the following command (SimplePerf environment initialization reference android.googlesource.com/platform/sy… In this article, app_profiler.py is the SimplePerf tool.)

python app_profiler.py -p com.aboback.wanandroidjetpack
Copy the code

After executing the above command, you need to manually start the App on the phone, and then actively stop

$ python app_profiler.py -p com.aboback.wanandroidjetpack
INFO:root:prepare profiling
INFO:root:start profiling1
INFO:root:run adb cmd: ['adb', 'shell', '/data/local/tmp/simpleperf', 'record', '-o', '/data/local/tmp/perf.data', '-e task-clock:u -f 1000 -g --duration 10', '--log', 'info', '--app', 'com.aboback.wanandroidjetpack']                                simpleperf I environment.cpp:601] Waiting for process of app com.aboback.wanandroidjetpack
simpleperf I environment.cpp:593] Got process 32112 for package com.aboback.wanandroidjetpack
Copy the code

After fetching, the parsing script is called to generate the HTML report

python report_html.py
Copy the code

You get this one down here

You can see not only the Java layer stack, but also the Native stack. This is just a simple use. For more details, please refer to the following documents

Preliminary test SimplePerf android.googlesource.com/platform/sy…

  1. The Android application profiling android.googlesource.com/platform/sy…
  2. The Android platform profiling android.googlesource.com/platform/sy…
  3. The Executable commands reference android.googlesource.com/platform/sy…
  4. Scripts reference android.googlesource.com/platform/sy…

4. Position of other components in Systrace when they start

4.1 Starting the Service

public final void scheduleCreateService(IBinder token,
        ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
    updateProcessState(processState, false);
    CreateServiceData s = new CreateServiceData();
    s.token = token;
    s.info = info;
    s.compatInfo = compatInfo;
    sendMessage(H.CREATE_SERVICE, s);
}

public final void scheduleBindService(IBinder token, Intent intent,
        boolean rebind, int processState) {
    updateProcessState(processState, false);
    BindServiceData s = new BindServiceData();
    s.token = token;
    s.intent = intent;
    s.rebind = rebind;
    sendMessage(H.BIND_SERVICE, s);
}
Copy the code

As you can see, all code execution is sending a Message to the H Handler, so if we start a Service in our code, it is not executed immediately, but is determined by the order of messages in the MessageQueue

If you zoom in on the actual execution, you can see that the execution takes place after the MessageQueue is executed in Message order (in this case, after the first frame of application has been executed), which then applies its own Message, starts the Service, and executes the broadcast receiver

4.2 Executing your own Message

Perform custom Message display in Systrace

4.3 to start the Service

Display of Service startup in Systrace

4.4 start the BroadcastReceiver

Performs the display of Receiver in Systrace

Broadcast registration: Normally registered in an Activity lifecycle function, executed where registered

4.5 Startup time of the ContentProvider

5. Can AppStartup optimize startup speed?

Initialization of the tripartite library

Many tripartite libraries need to be initialized in the Application and get the context of the Application incidentally

But there are libraries that don’t need to be initialized by ourselves, that are initialized by stealth, by using ContentProvider, defining a ContentProvider, and then getting the context in onCreate, and then doing the initialization of the library itself. One step in the APP startup process is to execute the onCreate method of all registered ContentProviders in the APP, so the initialization of the library is silently completed.

This is a great convenience for developers of integration libraries, and many libraries now use this approach, such as Facebook, Firebase, and WorkManager

The initialization timing of the ContentProvider is as follows:

However, when most tripartite libraries are initialized in this way, there are several problems

  1. There are too many ContentProviders during startup
  2. The application developer has no control over the initialization timing of libraries that are initialized this way
  3. Unable to handle these tripartite library dependencies

AppStartup library

In view of the above situation, Google launched AppStartup library, the advantages of AppStartup library

  • You can share a single Contentprovider
  • You can explicitly set the initialization order
  • Use this library to remove the automatic initialization of the third-party library’s ContentProvider startup step and manually start it with LazyLoad to optimize startup speed

Using the AppStartup library does not significantly speed up AppStartup, as measured, unless you have a large number of contentproviders (50+) that start at startup

If a third-party SDK uses a ContentProvider initialization time, then you can consider delaying initialization for the ContentProvider, for example

<provider
    android:name="androidx.startup.InitializationProvider"
    android:authorities="${applicationId}.androidx-startup"
    android:exported="false"
    tools:node="merge">
    <meta-data android:name="com.example.ExampleLoggerInitializer"
              tools:node="remove" />
</provider>
Copy the code

ExampleLoggerInitializer meta-data adds a Tools :node=”remove” flag

conclusion

  1. App Startup is designed to solve the problem that different libraries use different ContentProviders for initialization, resulting in too many ContentProviders, messy management, and time-consuming problems
  2. How much time is saved by App Startup: according to tests, if 20 or 30 libraries are integrated with App Startup, the time is reduced by less than 20ms
  3. The usage scenario of App Startup should be
    1. APK has a number of contentProviders initialized at startup
    2. Some of the tripartite libraries in APK are time-consuming to initialize, but do not have to be initialized at startup
    3. Application developers want to control when or in what order each library is initialized

App developer students need to verify

  1. Check the configuration file of the packaged APK for a look, How many tripartite libraries are initialized using ContentProvider (or open Merged Manifest at the bottom of the SRC \main\ androidmanifest.xml file of AS)
  2. Determine how long these ContentProviders take to start
  3. Identify which ContentProviders can be lazy-loaded or time-loaded
  4. If necessary, access the AppStartup library

6. Use IdleHandler in App startup scenarios

In the process of starting optimization, the idleHandler can execute tasks when the MessageQueue is idle, as shown in the following figure. You can clearly see the idleHandler execution timing

The usage scenarios are as follows:

  1. During startup, you can use idleHandler to do lazy loading.For example, addIdleHandler in the onCreate of the Activity during startup can be used to perform this task when Message is idle

  2. Collect statistics about the startup time: After fully loaded on the page, for example, invoke activity. ReportFullyDrawn this activity has been fully loaded to inform system, users can use, such as the following example, the home page of the List after completion of loading, Call activity. ReportFullyDrawn

    The corresponding Systrace is as follows

    The cold startup time of the resulting application is normal

Some system functions, also will depend on the FullyDrawn, so suggest active report (namely active call activity after the App in full swing. The reportFullyDrawn), there will be some additional benefits, such as speed up the launch (iorap)

series

  1. Systrace Response speed Combat 1: Understand the principle of response speed
  2. Systrace Response Speed Combat 2: Response speed Combat analysis – Take start speed as an example
  3. Systrace Response speed Combat 3: Response speed extension knowledge
  4. Systrace Basics – put a link here so you can click on it directly

Refer to the article

  1. Android application startup process analysis
  2. To explore the | App Startup can really reduce Startup time consuming
  3. New member of Jetpack, App Startup
  4. App Startup
  5. Android App startup optimization full record
  6. Android application profiling

About my && blog

  1. About me, I really hope to communicate with you and make progress together.
  2. Blog Content navigation
  3. Excellent Blog Post record – Android performance optimization is a must