App cold start

There are many ways to launch an App, and the one developers can optimize is usually a cold launch.

  • Cold start: Starts the App without being created. This process creates the process, starts the Application, and then starts the main Activity.
  • Cold start time: generally controlled in 2,3,5 seconds (2 seconds normal,3 seconds ok,5 seconds to the user tolerance limit).

This article discusses application scenarios

In actual development, some apps only have one Activity during startup, Namely AndroidManifest. There is a label for XML action android: name = “android. Intent. Action. The MAIN” Activity is the ultimate home page, this start-up time is more convenient, You can solve this problem by using command line statistics. However, some apps have multiple activities in the startup process. For example, some initialization operations are carried out first or the home page is entered after the animation is played. This article will discuss such situations. In the case of multiple activities, using the command line to measure the time of each Activity, and then adding it up, the result is not accurate or user-perceived. Therefore, the calculation method discussed in this paper applies to the following scenarios:

  • There is more than one Activity in the startup process.
  • This measure is not the actual cold start time conceptually, but the time from the creation process to the actual front page display from a user perception perspective.
  • Instead of executing the command line to do the calculation, you write code to do the calculation between start points.

There are several ways to evaluate an Activity during the startup process

Measure the time required to create the process, start the Application, and start the Activity during the App startup process. By understanding the startup process of App, find out the starting time of the following measurements:

  • In the Application ofattachBaseContext()Start counting the first part of the startup time in the first ActivityonCreate()This is the Application startup time, represented by coldTime in the example code below
  • In the first ActivityonCreate()Start counting the second part of the time in the following example code using hotTime, and then in the actual home page of the ActivityonWindowFocusChanged()End the calculation.
  • The total time is the sum of coldTime plus hotTime

code

Without further ado, let’s get right to the code.

For measurement convenience, first write a calculation time class

import java.util.HashMap;

public class TimeUtils {
    private static HashMap<String, Long> sCalTimeMap = new HashMap<>();
    public static final String COLD_TIME = "cold_time";
    public static final String HOT_TIME = "hot_time"; public static long sColdTime = 0; * @param Key Event name */ public static void beginTimeCalculate(String key) {long currentTime = System.currentTimeMillis(); sCalTimeMap.put(key, currentTime); } /** * get the running time of an event ** @param key event name * @returnReturns the elapsed time of an event that was called without {@link being called#beginTimeCalculate(String)} returns -1
     */
    public static long getTimeCalculate(String key) {
        long currentTime = System.currentTimeMillis();
        Long beginTime = sCalTimeMap.get(key);
        if (beginTime == null) {
            return- 1; }else {
            sCalTimeMap.remove(key);
            returncurrentTime - beginTime; Public static void clearTimeCalculate(String key) {public static void clearTimeCalculate(String key) { sCalTimeMap.remove(key); } /** * clear the start time */ public static voidclearStartTimeCalculate() {
        clearTimeCalculate(HOT_TIME);
        clearTimeCalculate(COLD_TIME);
        sColdTime = 0;
    }
Copy the code

Once you’ve written the utility class, start writing the time code. The following Log print code is written for testing convenience and can be ignored.

Step 1: Add code to the attachBaseContext() method of the Application:

 @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        if(is the main process) {/ / to the main process can TimeUtils beginTimeCalculate (TimeUtils. COLD_TIME); / / this Log. E ("beginTimeCalculate"."Start recording cold start time"); }}}Copy the code

Step 2: Execute the following code in the onCreate() method of the first Activity

 private void calculateStartTime() {
        long coldTime = TimeUtils.getTimeCalculate(TimeUtils.COLD_TIME);
        Log.e("coldTime"."Cold start time"+coldTime); // Timeutils. sColdTime is the time when the Application starts. coldTime : 0; TimeUtils.beginTimeCalculate(TimeUtils.HOT_TIME); // start counting hotTime}Copy the code

Step 3: Add the following code to the onWindowFocusChanged() method of the real home page Activity:

Public void onWindowFocusChanged(Boolean hasFocus) {Override public void onWindowFocusChanged(Boolean hasFocus)ifThe judgment condition is addedif (hasFocus) {
            long hotTime = TimeUtils.getTimeCalculate(TimeUtils.HOT_TIME);
            Log.e("hotStartTime"."Hot start time"+hotTime);
            if(timeutils. sColdTime > 0 && hotTime > 0) {// True cold start time = Application start time + hotTime Long coldTotalTime = TimeUtils.sColdTime + hotTime; Log.e("coldTotalTime"."Cold start time"+coldTotalTime); // Filter out abnormal startup timesif(coldTotalTime < 50000) {// coldTotalTime}}else if(hotTime > 0) {// Filter out abnormal startup timeif(hotTime < 30000) {// Upper heat transfer start time hotStartTime}}}}Copy the code

Write the code to run, look at the Log print, you can know the startup time. Above is the need to start App under normal circumstances, other abnormal circumstances are not discussed. There will be a certain deviation in each measurement, so it is necessary to take the average of multiple measurements. There is about 20% inaccuracy in measuring the startup time, but we can still determine whether optimization is needed by this time.

Knowing the startup time will help us to optimize the startup time of the App. Maybe it is because the optimization of 1s can win more users’ stay, which is also technical progress and responsible for the project. Let’s take action together.