Android optimized cold-start parsing

Foreword

In the event two days before the contract on the line, when moving in a certain test cloud, suggesting that cold start speed is lower than the average of the problem, before myself have tried to optimize, but found that the effect is not very obvious, as a pursuit developers, taking advantage of a little free time to look carefully at cold start optimization problem.

App startup process

We can look at the official document that describes "App startup time" to start the App. Application launch into a cold start, hot start, warm start. The Cold Start is an application from scratch, which involves a more complex knowledge. This time we mainly on cold start applications for analysis and optimization. Application in cold start, you need to perform the following three tasks:

  • Load and launch applications;
  • Demonstrate a blank window immediately after the start App starts;
  • App creation process procedures;

After three tasks to perform, the system creates the application process, the application process will be the next step:

  • App created objects;
  • Start Main Thread;
  • Creating Activity start page;
  • Load View;
  • Screen layout;
  • Initial drawing;

After completion of the initial application process mapping, system process to replace the background window with the currently displayed page Activity start, this time the user can use the App. The following figure shows the workflow system and applications.

From the above steps and the figure we can see, the application process is created, it will certainly execute our Application life cycle , when the application process created App, the main thread will initialize our first page MainActivity and execution MainActivity the life cycle . I deliberately bold focus, this is what we can start to optimize part. Before how to optimize the analysis, we can first look, our application is not required to optimize cold start.

PS: In fact, these are the things that we see the surface, if we need to complete to get to the bottom, we're going to analyze Zygote Fork specific process, ActivityManagerService source code, and we would not elaborate in this chapter, to recommend books, there are Luo Sun's "Android system source code scenario analysis", Liu Wang Shu of "Android Advanced decryption."

Start time detection

So how much is the right time to start it? In the official documentation to describe when a cold start in 5 seconds or longer, Android vitals will consider your application needs associated with optimizing cold start. But Android vitals is an app for the Google Play quality testing tool, we all know that, like me, but you can use Ali cloud of mobile testing, data provided by Ali cloud, industry indicators median cold start is 4875.67 ms, we can compare, where appropriate. Well, here we talk about if we detect cold application startup time.

Displayed Time

Displayed Time As indicated in Figure 1, the Android 4.4 (API level 19) and later, logcat log contains information named Displayed This value indicates the boot process is completed and the drawing elapsed between the respective activity on the screen The amount of time.

ADB command

 

adb shell am start -W [packageName]/[packageName.MainActivity]

In a way Displayed Time using the log print station, we saw Displayed in the log, followed by the following is what we need [packageName] / [packageName.MainActivity], we can directly use the copy, and then we stuck in Terminal AS then print data is time we start the specified page.

 

Status: ok
Activity: com.xx.xxx/com.xx.xxxx.welcome.view.WelcomeActivity
ThisTime: 242
TotalTime: 242
WaitTime: 288
Complete

  • ThisTime: it refers to the process of calling the last Activity start time to the end of startActivityAndWait call this Activity;
  • TotalTime: refers to the process of calling the first Activity start time to the end of the last Activity startActivityAndWait.
  • WaitTime: startActivityAndWait this method is time-consuming calls;

reportFullyDrawn

In some special scenes, we could not just start drawing page completion callback time is enough, we need to start even after the splash screen advertising interface data page be considered a complete success callback time, then we can use reportFullyDrawn

 

public class WelcomeActivity extends MvpActivity<WelcomePresenter> implements WelcomeMvp.View {
 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_welcome);
 // 请求数据
 mvpPresenter.config();

 }
 @Override
 public void finishRequest() {
 // 数据回调
 reportFullyDrawn();
 }
}

PS: This way minSdkVersion need API19 +, so to be set to the SDK version or judgment.

Traceview

Traceview is a very easy to use performance analysis tool for Android devices, it can be a detailed interface that allows us to track the performance of the program, and can clearly see the number of time-consuming and call each function.

systrace

Systrace very intuitive display the calling sequence for each thread above the API and time-consuming cases.

Traceview and Systrace are DDMS tool panel, but now more than AS3.0 version is no longer recommended, so would not elaborate here, if students are interested, you can read my previous article smooth "Android application of optimization of practical operation ", which has described in detail the use of these two tools.

hugo

github.com/JakeWharton…

We can use the JakeWharton hugo, acquisition time corresponding to the class or function consumed by way of annotations. We can use it to start page Activity lifecycle to pull the details.

Start optimization practical operation

User Experience Optimization

In the cold start-optimized experience personally think is the elimination of the main black and white / black screen at startup, because the black and white / black for the first impression the user is slow, Caton. We can set the startup page theme to achieve their goals.

 

<style name="WelcomeTheme" parent="Theme.AppCompat.Light.NoActionBar.FullScreen">
 <item name="android:windowBackground">@drawable/shape_welcome</item>
 <item name="android:windowDrawsSystemBarBackgrounds">false</item>
</style>

windowDrawsSystemBarBackgrounds portion is provided with a column system operation. This is followed by layout window background color;

 

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque">
 <item android:drawable="@android:color/white"/>
 <item>
 <bitmap
 android:src="@drawable/welcome_bg"
 android:gravity="center"/>
 </item>
</layer-list>

Ads start page to show complete jump to the home page, and then we set back our common styles can be set in code in the manifest file;

 

<activity
 ···
 android:theme="@style/AppBaseFrameTheme"/>

By setting the theme for the launch page, they will be black and white / black to erase, the user clicks on the icon on the display of App start drawing, allowing users to quickly start generating "illusion." At the same time there can be animated, so that the transition between the start page and home page more natural.

Application start optimization

From the analysis are summarized on a map, I was bold tips for optimizing point Application life cycle, and then we come back to this part of the optimization operate.

Application#attachBaseContext()

Application will start after attachBaseContext () -> onCreate (); At this time we think of the life cycle from attachBaseContext to what? Yes that is MultiDex subcontracting mechanism. Then surely we will find, since the number of ways we deal with subcontracting exceeds 65535, start black and white / black screen problem arises, subcontracting mechanism is an important reason leading to a cold start slow, and now part of the application using the plug-oriented approach MultiDex to avoid problems caused by black and white, although this is a way, but the development cost is too high for many applications is unnecessary. Let's talk about MultiDex optimization, first of all MultiDex compile-time and two part can be divided into runtime:

  • Compile: in the App class to be split across multiple dex a strategy in order to reduce the number of the first main class dex dex also included;
  • Runtime: when App starts, the virtual machine to load only the main dex in class. After app start using Multidex.install, to load the ClassLoader other modifications dex dexElements by reflection;

From a practical analysis of many articles online, they mainly used in asynchronous mode. App will load first start since the main dex package, then we will be free to handle subcontracted work, we will start the main class home page and required libraries, components and other main points in dex in order to achieve the fine points of the main dex package size, wording specific operation, you can refer to online MultiDex start optimization article, but we should note that in the course of the main sub-dex, the main dex through our range of optimized operation reduces the size of the main dex, and therefore increases abnormalities may NoClassDefFoundError at this time will lead to risk our application failed to start, so we must do a good job in the optimization test work.

Application#onCreate()

After attachBaseContext () after the onCreate () life cycle, presumably most of our applications, will be initialized to work for our use of third-party libraries and components here. Due to the continuous iterative version, initialization third-party libraries are written directly in onCreate (), a large number of initial work led to the life cycle is too heavy, we should classify these third-party libraries. Here is my finishing our job classification App started:

Looked on the map, a variety of third-party tools and business logic initialization initialization, affect the start time. Let them be split into four parts.

  • You must be in onCreate () and is the main process initialization
  • It can be delayed, but need to be initialized in Application
  • Initialization callbacks can be delayed until the start page of the Life Cycle
  • With a time delay to re-initialize

We can according to their own projects listed first initializes itself every project, and then classified. Although I have not posted here a specific operation code, not I think a new thread or create a IntentService too easy not say, but here things need to be noted that the optimization of the entire cold start up, because he stepped on is here pit. For example a GrowingIO, when the project using a very old version of the GIO, GIO is then initialized on the child thread operations, before suddenly contracting, operations departments SDK version needs upgrading the GIO, after Seung feel compile and run nothing to do directly packaged, operational feedback to the line after the new version did not circle the data, after examination revealed a new version of the GIO is not initialized in the child thread. From this lesson, the students I think since you are interested in optimizing cold start, it is certainly not bad that a few copy and paste the code, which are to specific conditions. Let me summarize the focus

  • Start slow, is not no brain open thread, and then plug the code on the bin, you need the right medicine;
  • Open thread is a science, Thread, ThreadPoolExecutor, AsyncTask, IntentService, select exactly what;
  • Suppose you good new Thread, but did not consider a good memory leaks, do not just fill the pit while digging;
  • Note that some third-party SDK needs to be initialized in the main thread;
  • If the application is multi-process, aware that some third-party SDK, you need to be initialized in the package with the same name process;
  • In fact, there are a lot of projects, after years of iterative version of the code are not finishing off those old code, the code is useless to classify and organize the needs;

Activity start page optimization

  1. We start page layout optimization Activity includes start drawing controls, map controls splash screen advertising, video advertising splash screen controls, map controls introduced for the first time installation. For layout optimization, in addition to start drawing controls, the other is not to be initialized when App start control, then we can use ViewStub. For specific business scenarios, initialize the specified control.
  2. Avoid I / O operations we know I / O operation is not real-time, such as reading and writing database, SharedPreferences # apply (). We should note that these actions have not block the main thread to perform, and we can take advantage of StrictMode strict mode, which allows you to detect when we started there is no disk read and write properly.
  3. Note picture bitmap loading speed and encoding formats that we can know, in most cases start page is displayed pictures, then how do we pull the details in this regard the picture of it, and that is the choice to load the library for a variety of third-party images Glide, Picasso, Fresco, etc., there is PREFER_ARGB_8888, PREFER_RGB_565 selection problem, we can choose the case for their own projects.
  4. The core of the vector using vector graphics VectorDrawable object is to save time, save space. For some users, it may not start drawing a picture, it is very simple, just a logo, this time we can consider the use of vector graphics.
  5. Note that the callback start lifecycle Activity in our Application # onCreate () optimization, certain not very necessary network request and moved to welcome page, but we can not directly operate the network requests directly copied to the start page onCreate (), we can skillfully use Activity lifecycle Activity # onWindowFocusChanged (boolean hasFocus), this is true of all the controls you initialize the callback, we can operate on the network here, of course, we can also use the Service.

Cold start optimization summary

For optimizing cold start, we need to go step by step analysis, unlike the copy layout optimization routine is so, so many times the term bottleneck bottlenecks appear in the official document describes our way of optimizing cold start will not level ground, we have to make good use of Android Studio's CPU profiler (we have the opportunity to analyze in detail the use of this feature), because a lot of online summary by Traceview and Systrace, but the two have been discarded in AS3.0 version of the upgrade, we want to reflect the side of the ground see the official documents, with their first Android angle to think about change, not through someone else's translation analysis. Finally, we encourage each other what is more competitive in today's Android market, how to win in contrast to competing products, we also need a step by step to one of the details of the well to do perfectly.

The share is that these, feel good welcome attention, the latter continued to share Android technology and advanced information and other dry goods

Published 56 original articles · won praise 1 · views 2905

Guess you like

Origin blog.csdn.net/chuhe1989/article/details/104663865