Today I’m going to share with you a performance optimization experience, mainly in the Activity startup aspect. As we all know, providing users with immediate response is an important part of enhancing user experience on mobile devices. During the startup process, an Activity will undergo at least three callback processes: onCreate(), onStart(), and onResume(). In these three processes, it will experience the actual operation of drawing interface, loading data, recovering site and so on. This has an impact on how much an Activity starts. Generally speaking, we try to optimize the Activity startup speed by working on the above three callbacks, thinking that if the above operations are optimized well enough, we can have a good experience. The same is true for us to search on Baidu to improve the speed of Activity launch.

For complete code, see Complete Code

Now let’s look at another aspect of the problem. Here’s an animation:

Notice that after clicking “Launch SecondActivity”, the interface freezes for a few seconds before jumping. SecondActivity itself does nothing, as shown below:

public class SecondActivity extends Activity { private final String TAG = getClass().getSimpleName(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); Log.d(TAG, "onCreate end"); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart end"); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume end"); }}Copy the code

This is a very extreme case, in each lifecycle of the startup process, all you do is output Log, but you still get stuck. Let’s look at what we did in the Activity that started it:

@Override protected void onPause() { super.onPause(); sleep(); } // Sleep 5000 ms in main thread. private void sleep() { if (needSleep) { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code

In onPause(), we implemented a 5000ms mainthread delay to simulate a large number of mainthread operations, and we found that too much work during onPause can cause subsequent Activity starts to be delayed. This explains why we repeatedly optimize the Activity that is about to launch with little success. Once the onPause() method is inactive, or the actual project is short, subsequent activities can start very quickly, as shown in the following example:

Hope that through the above description, to provide readers with another performance optimization scheme. Demo APK and source download: github.com/wh1990xiao2…