• Do development in addition to the implementation of functions, but also pay attention to optimization, performance optimization includes a lot of things, package size, startup speed, memory, data structure, ANR, and so on.
  • Users all hope that when the APP is pressed, it can be used immediately on the home page. The performance of the phone is very important, but users cannot be asked to change their phone. Therefore, we need the APP to find ways to optimize the startup speed, or the APP may be deleted.
  • Android performance Optimization – Stalling and layout optimization can be learned together.

1. Startup status

  • Our APP is not as big as wechat, so it is almost impossible for manufacturers to make special arrangements for us and keep hanging there. In most cases, it is cold start, and optimization is mainly optimized cold start.
  • Cold start

In cold startup, an application starts from the beginning: The system processes create application processes after cold startup. Cold startup occurs when the application is started for the first time after the device is started or the application is terminated.

  • Warm start

In a hot start, all the system does is bring the Activity to the foreground. As long as all of the application’s activities remain in memory, the application does not have to perform object initialization, layout loading, and drawing repeatedly. Like go back to the desktop and come back in time without killing the APP.

  • Wen started

A warm start contains some of the actions that occur during a cold start; At the same time, it is more expensive than hot boot. There are many potential states visible as warm starts. For example: 1. The user exits the application and then restarts the application. The process may not be destroyed and continue running, but the application needs to execute onCreate() to recreate the Activity from scratch. 2. The system frees the application from memory, and the user restarts it. The process and Activity need to be restarted, but the saved instance state bundle passed to onCreate() helps to do this.

2. Cold startup time

  • The 2-5-8 principles:
  • When users can get a response within 2 seconds, they will feel that the response of the system is fast.
  • When the user gets the response between 2-5 seconds, the response speed of the system will feel ok;
  • When users get a response within 5-8 seconds, they will feel that the response speed of the system is slow but acceptable.
  • When the user still doesn’t get a response after more than 8 seconds, the system feels terrible or unresponsive.

2.1 System Log Statistics

  • If you go to Logcat, filter Displayed, you can see the startup time.
  • This is how long it takes for the application to start until the corresponding Activity is drawn. (The following image shows starting MainActivity)

2.2 ADB Command Statistics

  • Adb requires environment variables to be configured. Simply add the platform-tools path from the SDK directory to the environment variable path.

  • adb shell
  • am shart -S -W com.bao.myapplication/.MainActivity
  • Type these two commands based on your package name and the Activity you want to start to see the start time.
  • TotalTime is the startup time.

3. Start the analysis

  • Check CPU activity with CPU Performance Profiler for details.

3.1 CPU Profile Tool simple tutorial

  • As Android Studio becomes more functional, we can use CPU profiles to see what is being done at startup.
  • Go to App -> Edit Configurations.

  • Profilling -> Start recording CPU activity on startup.
  • Select CPU record to configure Trace Java Methods.

  • These four modes are also detailed in the official documentation.
  • 1. Java method sampling: Frequently capture the application call stack during the execution of the application’s Java code. The analyzer compares the captured data sets to derive time and resource usage information related to the execution of the Java code applied.

An inherent problem with sample-based tracing is that if an application enters a method after capturing the call stack and exits the method before the next capture, the analyzer will not record the method call. If you want to track a method with such a short life cycle, use peg tracing.

  • 2. Trace Java methods: Detect the application at run time to record a timestamp at the beginning and end of each method call. These timestamps are collected and compared to generate method trace data, including time information and CPU utilization.

Note that the overhead associated with detecting each method affects runtime performance and may affect analysis data; This is especially true for methods with relatively short life cycles. In addition, if an application executes a large number of methods in a short period of time, the analyzer may quickly exceed its file size limit and cannot record any more trace data.

  • 3. Sampling C/C++ functions: Capture the sample trace data of the application’s native thread. To use this configuration, you must deploy the application to a device running Android 7.0 (API level 24) or higher.

Internally, this configuration uses Simpleperf to track the application’s native code. If you need to specify other options for Simpleperf, such as sampling for a specific device CPU or specifying a high-precision sampling duration, you can use Simpleperf from the command line.

  • 4. Trace system calls: Capture very detailed details that allow you to examine how your application interacts with system resources. You can check the exact time and duration of thread state, visually see where the CPU bottlenecks are for all cores, and add custom trace events to analyze. This kind of information is critical when you troubleshoot performance problems. To use this configuration, you must deploy the application to a device running Android 7.0 (API level 24) or higher.

When using this trace configuration, you can visually flag important code routines on the analyzer timeline by detecting the code. To detect C/C++ code, use the native trace API provided by trace.h. To examine Java code, use the Trace class. For more details, see Testing your application code.

This trace configuration is based on systrace. You can use the Systrace command line utility to specify options other than those provided by the CPU performance profiler. Additional system-level data provided by Systrace can help you examine native system processes and troubleshoot frame loss or frame delay problems.Copy the code
  • Once set up, launch the Profile.

  • When you see your APP’s CPU usage is low, you’re almost done with startup, hit Stop.

3.2 Analysis of startup Time

  • Call Chart double-clicks the thread to see how long it took the method to execute, from top to bottom, except for the system method, which is in green and has its own code, to see how long it took. The methods here are arranged in timeline, from startup to completion.

  • The Top Down tag displays a list of calls from which expanding a method or function node shows its callees. As you can see in the image below, I placed a thread. sleep in the custom View and it went to sleep for 3 seconds.

  • The horizontal Flame Chart represents the method duration and the upward one is the method being called. We can also see that the sleep in the custom View is significantly longer than the others.

3.3 Using the Debug Api to Generate. Trace Files

  • Add debug.startMethodTracing () to the Application onCreate method.
  • Add debug.stopMethodTracing () to the MainActivitu onWindowFocusChanged(Boolean hasFocus) method.
public class BaoApplication extends Application {

    @Override
    public void onCreate(a) {
        super.onCreate();
        Debug.startMethodTracing("baoTest"); }}public class MainActivity extends AppCompatActivity {...@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ...}/** * MainActivity stops where analysis is started *@param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus); Debug.stopMethodTracing(); }}Copy the code
  • By default, the.trace file is generated in your application directory and copied to your PC directory.

  • Drag it to Android Studio to see the results.

4.StrictMode StrictMode

  • Turn on harsh mode during development and remind us.
  @Override
    public void onCreate(a) {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            // Thread detection
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads()
                    .detectDiskWrites()
                    .detectNetwork()
                    .penaltyLog()
                    .build());

            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectLeakedSqlLiteObjects()// Database object leaks
                    .detectLeakedClosableObjects()// Unclosed objects leak
                    .penaltyDeath()// Break the rules
                    .penaltyLog()// Violation log.build()); }}Copy the code

5. At the end

  • Simplify the layout by not having too many levels of layout to improve startup speed (skilled use of constraint layout can reduce the number of levels), and do not do time-consuming startup and main thread operations.
  • Start as far as possible not to engage in what sleep hibernation, even if not error, but also bad search.
  • Some apps will have launch ads, and we can continue the initialization work by using child threads during the time the AD is displayed.
  • There are a lot of start-up processes, which are also very complicated. Generally, what we can change is our APP. We can use tools to analyze which parts of our APP are time-consuming, and try to reduce as much as possible.