Android performance optimization – startup optimization improved by 60%

Application startup speed

The startup speed of an application can affect the user’s first experience. An application with a slow startup speed (perceptually) may cause the user to decrease the intention to open the app again, or uninstall and abandon the application.

This article will optimize the application startup speed from two directions:

1. Visual experience optimization 2. Code logic optimization

Visual optimization

There are three states of application startup, each of which affects how long it takes for the application to be visible to the user: Cold Start, Warm Start, and Warm Start

For these three startup methods, you can view the Google development documentation

What everyone often talks about is cold start and hot start

1. Cold start: When an application is started, there is no process of the application in the background. At this time, the system will re-create a new process and assign it to the application. This startup method is cold start2. Warm start: When starting an application, there is already a process of the application in the background (for example: press the back key or home key. Although the application will exit, the process of the application will still remain in the background and you can enter the task list. View), so if there is an existing process, this startup will start the application from the existing process. This method is called hot start.

On a cold start, the application starts from scratch. In other states, the system needs to bring a running application from the background to the foreground. We recommend that you always optimize based on cold start assumptions. Doing so will also improve hot and warm start performance

At the beginning of a cold boot, the system has three tasks. These tasks are:

1. Load and start the application 2. Display a blank startup window of the application immediately after startup 3. Create an application process

Once the system creates an application process, the application process is responsible for the next phases, which include:

1. Create the app object 2. Start the main thread (main thread) 3. Populate and load the layout Views 4. Execute the drawing process of the View on the screen. measure -> layout -> draw

After the application process completes its first draw, the system process swaps the currently displayed background window, replacing it with the main activity. At this point, the user can start using the application

Because the creation process of the App application process is determined by the software and hardware of the mobile phone, we can only visually optimize during this creation process.

Start theme optimization

The so-called theme optimization is to set the theme of the startup window when the application is cold started (stage 1~2).
Because now when the App is started, it will first enter a splash screen page (LaunchActivity) to display the application information.

By default, a white screen will appear. By default, the system will start a blank window when the application is started until the entry Activity of the App application is successfully created. After the view is drawn, the system will start a blank window by default when the application is started. Until the App The entry Activity of the application is created successfully and the view is drawn. By default, the system will start a blank window when starting the application until the entry Activity of the App is created successfully and the view is drawn.

The solution can be found in the implementation method of Android startup interface SplashActivit

Code optimization

How to calculate app startup time in Android

According to the output statistics of the startup time above, we can first record the cold start time before optimization, and then compare the startup time after optimization.

Application optimization

Application, as the entire initialization configuration entry of the application, often bears a burden that it should not have ~

There are many third-party components (including the App application itself) that seize the opportunity in Application to complete the initialization operation.
However, completing heavy initialization operations and complex logic in Application will affect the startup performance of the application.
Often, there are opportunities to optimize these efforts to achieve performance improvements, and these common issues include:

1. Complex layout initialization 2. Blocking main thread UI drawing operations, such as I/O reading and writing or network access 3. Bitmap large pictures or VectorDrawable loading 4. Other operations that occupy the main thread

We can classify initialization according to the priority of these components.

1. Necessary components must be initialized immediately in the main thread (the entry Activity may be used immediately) 2. Components must be initialized in the main thread, but initialization can be delayed 3. Components can be initialized in child threads

It is recommended to delay initialization for component initialization placed in child threads so that you can understand whether it will affect the project
So for the above analysis, we can optimize the loading component of Application in the project as follows:

  • Put components such as Bugly, x5 kernel initialization, SP reading and writing, and Umeng into child threads for initialization. (Sub-thread initialization cannot affect the use of components)
new Thread(new Runnable() {
            @Override
            public void run() {
                //Set the priority of the thread and do not compete with the main thread for resources.
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //Sub-thread initializes third-party components
                Thread.sleep(5000);//It is recommended to delay initialization. You can find out whether it affects other functions or crashes!
            }
        }).start();
  • Delay loading of actions that need to be initialized in the main thread but do not need to be completed immediately (originally I wanted to do this in the entry Activity, but it is better to put the initialization of the component under unified management in the Application)
handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //Lazy initialization component
            }
        }, 3000);

Business optimization of splash screen pages

In the end, there are only a few components left to initialize actions on the main thread, such as buried points, click streams, database initialization, etc., but the time consumed can be offset in other places.

Requirement background: Apps usually set a fixed splash screen page display time, such as 2000ms, so we can adjust the display time according to the running speed of the user’s mobile phone, but the total time is still 2000ms

Total splash screen page display time = component initialization time + remaining display time

That is, the total time is 2000ms. The component is initialized for 800ms, so it can be displayed for another 1200ms.

After the Application is initialized, the attachBaseContext() method will be called, and then the Application’s onCreate() will be called, and then the entry Activity will be created and executed onCreate() method. So we can record the startup time in Application

//Application
@Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        SPUtil.putLong("application_attach_time", System.currentTimeMillis());//Record Application initialization time
    }

With the startup time, we need to know the time when the entry’s Activity is displayed to the user (the View is drawn). The callback timing of onWindowFocusChanged() indicates that the user’s touch time and the View’s process drawing are completed, so we can use this method record display time

//Activity
@Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
  
          long appAttachTime = SPUtil.getLong("application_attach_time");
          long diffTime = System.currentTimeMillis() - appAttachTime;//The time from application to entry Activity
 
         //So the display time of the splash screen page is 2000ms - diffTime.
    }

Therefore, we can dynamically set the display time of the application splash screen, and try to make the display time of each mobile phone consistent, so that users with lower mobile phone configurations will not feel the long and arduous splash screen page time (for example, 2000ms is initialized, Also need to display a splash screen page time of 2000ms.) to optimize user experience

Advertising page optimization

After the splash screen page, the advertising page of the sponsor fathers will be displayed.
Because the advertising page images in the project may be large images or APng dynamic images, these images need to be downloaded to local files and then displayed after the download is completed. This process often encounters the following two problems:

  • Downloading advertising pages, because this is an asynchronous process, often does not know the appropriate time to load the page.
  • Saving the advertising page, because saving is an I/O stream operation, is likely to be interrupted by the user, and you will get a damaged picture next time.

Because the user’s network environment is unknown, it may take some time for some users to download the advertising page, and it is impossible to wait indefinitely at this time. So to solve this problem, we can enable IntentService to download advertising page images.

Enable IntentService in the entry Activity to download the advertising page. Or other asynchronous download operations

After the ad page image file stream is completely written, record the image size, or record an identifier.

During the next loading of the advertising page, you can determine whether the advertising page image has been downloaded and whether the image is complete. Otherwise, delete the image and download it again.

In addition, because there is still remaining display time in the splash screen page, if the user has downloaded the image and the image is complete during this time period, the advertising page can be displayed. Otherwise, enter the main Activity, because IntentService still continues to silently download and save pictures in the background~Original text https://juejin.cn/post/7283832557502365733?searchId=202311131413267F663526D2344736DBFD

On the business card at the end of the article, you can get free audio and video development learning materials, including (FFmpeg, webRTC, rtmp, hls, rtsp, ffplay, srs) and audio and video learning roadmap, etc.

See below! ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java skill treeUse JDBC to operate the databaseDatabase operation 139420 people are learning the system