Measure Android app startup time

后端 未结 9 921
Happy的楠姐
Happy的楠姐 2020-12-08 10:35

What is the most precise way to measure startup time of an Android app?

By startup time I mean the difference between 2. and 3. :

  1. The app process is no
9条回答
  •  不知归路
    2020-12-08 10:54

    It is possible to implement time tracking using the next code:

    Override your Application:

    public class CustomApplication extends Application {
        public final static long APP_START_TIME = System.currentTimeMillis();
    
        /**
         * Do all other application stuff
         */
    }
    

    And add few rows to your main Activity:

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final View contentView = findViewById(android.R.id.content);
            contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (Build.VERSION.SDK_INT >= 16) {
                        contentView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        contentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                    long launchTime = System.currentTimeMillis() - CustomApplication.APP_START_TIME;
                    Log.e("TEST", "App launch time = " + launchTime);
                }
            });
        }
    }
    

    And don't forget to define your custom application in Manifest:

    
    
    
    

    Important: You have to kill your application before launch, because Application stores static variable which tracks initial time.

提交回复
热议问题