Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to optimize Cold start in Android

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "how to optimize cold start in Android", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to optimize cold start in Android" article.

Start-up process of App

We can take a look at the description of App startup in the official document "App startup time". Application startup is divided into cold startup, hot startup and warm startup. Cold start is when the application starts from scratch and involves more complex knowledge. This time, we mainly analyze and optimize the cold start of the application. When the application starts cold, you need to perform the following three tasks:

Load and start the application

Immediately after App starts, a blank startup window is displayed

The process of creating an App program

After the execution of these three tasks, the system creates the application process, and the application process will perform the next step:

Create an App object

Start Main Thread

Create an Activity for the startup page

Load View

Layout screen

Make the initial drawing

When the application process finishes the initial drawing, the system process replaces the currently displayed background window with the Activity of the startup page, and the user can use App at this time.

From the above figure and the above steps, we can see that when the application process is created, it will certainly execute the life cycle of our Application. When the application process of App is created, the main thread will initialize the life cycle of our * page MainActivity and execution MainActivity. I've deliberately thickened the point, and this is where we can optimize it. Before analyzing how to optimize, we can first find out whether our application needs to optimize the cold start.

PS: in fact, these are all things we see on the surface. If we need to delve into the Zygote Fork process and ActivityManagerService source code in detail, we will not elaborate in this article. We will recommend relevant books to you, such as Luo Shengyang's "scenario Analysis of Android system Source Code" and Liu Wangshu's "Android Advanced decryption".

Startup time detection

So what is the right start-up time? It is described in the official documentation that when the cold start is 5 seconds or more, Android vitals will think that your application needs to be optimized for cold start. However, Android vitals is an application quality testing tool for Google Play, and we all understand that, but you can use Aliyun's mobile test like me. In the data provided by Aliyun, the median industry indicator for cold start is 4875.67ms, which you can compare as appropriate. All right, let's talk about if the cold start time of our application is detected.

Displayed Time

As shown in the Displayed Time shown in figure 1 above, in Android 4.4 (API level 19) and later, logcat contains a log information called Displayed, which represents the amount of time elapsed between the startup process and the completion of the corresponding activity on the screen.

ADB command

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

In the log print desk using the previous method Displayed Time, we see the log of Displayed, followed by the [packageName] / [packageName.MainActivity] we need below, which we can copy and use directly, and then we paste it in the Terminal of AS, and then print the startup time data of the page we specify.

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

ThisTime: refers to the time from the start of an Activity to the end of the startActivityAndWait call of this Activity during the call.

TotalTime: refers to the start time of * Activity to the end of * startActivityAndWait of an Activity during the call.

WaitTime: it is the call to startActivityAndWait that takes time

ReportFullyDrawn

In some special scenarios, we may not only have enough callback time to complete the drawing of the startup page, we need to calculate a complete time after the splash screen advertisement interface data of the startup page has been successfully called back, then we can use reportFullyDrawn

Public class WelcomeActivity extends MvpActivity implements WelcomeMvp.View {@ Override protected void onCreate (@ Nullable Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_welcome); / / request data mvpPresenter.config ();} @ Override public void finishRequest () {/ / data callback reportFullyDrawn ();}}

PS: this way minSdkVersion requires API19+, so you need to set or judge the SDK version.

Traceview

Traceview is a very useful performance analysis tool for Android devices, it allows us to track the performance of the program through a detailed interface, and can clearly see the time spent and the number of calls to each function.

Systrace

Systrace very visually shows the order and time-consuming of the API calls on each thread.

Traceview and Systrace are DDMS panel tools, but now the above version of AS3.0 is no longer recommended, so it will not be detailed here, if you are interested, you can see my previous article "Android application optimization flow fluency practice", which has a detailed description of the use of these two tools.

Hugo

Github.com/JakeWharton...

We can use the hugo of JakeWharton to get the time consumed by the corresponding class or function by annotating. We can use it to dig out the details of the life cycle of the startup page Activity.

Start the optimization operation

User experience optimization

In my opinion, the main experience of cold startup optimization is to eliminate the white / black screen at startup, because the white screen / black screen is slow and stuttered for users. We can set the theme of the startup page to achieve this goal.

WindowDrawsSystemBarBackgrounds is the setting of the system operation bar for some parts. Then there is the layout of the background color of the window.

The ad display of the startup page jumps to the home page, and then we set it back to our generic style, either in the manifest file or in the code.

After setting the theme of the startup page, the white / black screen will be erased, and the user clicks the App icon to display the startup map, giving the user the illusion of starting quickly. At the same time, you can use animation to make the transition between the startup page and the home page more natural.

Application startup optimization

From the analysis and summary of figure 1 above, I gave a bold hint to the life cycle of the optimization point Application, and then we came back to optimize this part.

1. Application#attachBaseContext ()

Application launches through attachBaseContext ()-- > onCreate (); what do you associate with the life cycle of attachBaseContext? Yes, it is the MultiDex subcontracting mechanism. I'm sure everyone will find that the problem of starting the white screen / black screen has appeared since we handled the subpackage by more than 65535. The subcontracting mechanism is an important reason for the slow cold start. Now some applications use plug-ins to avoid the white screen problem caused by MultiDex. Although this is a method, the development cost is really high, which is unnecessary for many applications. Let's talk about MultiDex optimization. First, MultiDex can be divided into run-time and compile-time parts:

Compilation time: split the class in the App into multiple dex with a certain strategy. In order to reduce the number of dex, the number of class contained in the main dex is also included.

Run time: when the App starts, the virtual machine loads only the class in the primary dex. After app starts, use Multidex.install to modify the dexElements in ClassLoader through reflection mechanism to load other dex

From the analysis of many practical articles on the Internet, they mainly adopt the asynchronous method. Because the App starts with loading the main dex package first, then we can handle the subcontracting work on our own. We divide the main libraries and components needed by the startup page and the home page into the main dex, so as to achieve the size of the main dex package. For specific operation, you can refer to the online MultiDex startup optimization article, but you should pay attention to the sub-process of the main dex. After a series of optimization operations, the main dex reduces the size of the primary dex, so it also increases the possibility of abnormal NoClassDefFoundError, which will lead to the risk of failure of our application startup, so we must do a good job of testing after optimization.

2. Application#onCreate ()

After attachBaseContext () comes to the onCreate () life cycle, presumably most of our applications will initialize the third-party libraries and components we use here. Due to the iteration of the version, the initialization of third-party libraries is written directly in onCreate (). A lot of initialization work makes the life cycle too heavy, so we should classify these third-party libraries.

Looking at the figure above, various third-party tool initialization and business logic initialization affect the startup time. Let's split them into four parts.

Must be initialized in onCreate () and in the main process

Can be delayed, but needs to be initialized in Application

Initialization can be delayed to the life cycle callback of the startup page

Delay initialization until it is in use

You can first list each initialization of your own project according to your own project, and then classify it. Although I didn't post the specific operation code here, it's not that I don't think it's too easy to new a thread or create an IntentService, but what I need to pay attention to here is the most cold start optimization, because I've stepped on a hole here. Take an example of GrowingIO. At that time, the project used a very old version of GIO. At that time, the initialization of GIO was operated on sub-threads. Before suddenly sending the package, the operation department proposed to upgrade the SDK version of GIO. After the upgrade, the compilation and operation felt that there was nothing directly packaged. After arriving online, the operator reported that the new version of GIO could not be initialized in sub-threads. From this lesson, I think that since you are all interested in cold start optimization, you will not be short of the copied and pasted code, which is a case-by-case analysis. Let me sum up the main points.

Start slowly, not mindless to open a thread, and then plug the code to finish, need to prescribe the right remedy to the case

Opening threads is also a subject, Thread, ThreadPoolExecutor, AsyncTask, IntentService, which one should you choose?

Suppose you new Thread, but have you considered the memory leak problem? don't dig the hole while mending the hole.

Note that some third-party SDK needs to be initialized in the main thread

If the application is multi-process, note that some third-party SDK requires you to initialize it with the same package name process.

In fact, there are many projects that have not sorted out the code after many years of version iteration, and the old code and useless code all need to be sorted out.

Optimization of startup page Activity

Layout optimization our startup page Activity contains startup control, splash screen advertisement control, splash screen advertisement video control, and * * installation diagram control. For layout optimization, except for the startup diagram control, none of the controls are initialized when App starts, so we can use ViewStub. Initializes the specified control for the specified business scenario.

To avoid I _ SharedPreferences#apply O operations we know that I _ map O operations are not real-time, such as database read and write, database (). We should pay attention to whether these operations block the execution of the main thread, and we can take advantage of the StrictMode strict mode, which can be used to detect whether we are correctly reading and writing to the disk at startup.

Pay attention to the picture bitmap loading speed and encoding format we can know, the launch page in most cases is the picture display, then how do we pick the details of the picture, that is, the choice of a variety of third-party picture load library Glide, Picasso, Fresco, etc., as well as the selection of PREFER_ARGB_8888, PREFER_RGB_565, we can choose for their own project.

The core of using vector graph VectorDrawable object is to save time and space. For some users, its startup diagram may not be a picture, it is very simple, just a logo, at this time we can consider the use of vector graphics.

Note the callback of the startup life cycle in Activity We optimized in Application#onCreate () to move some unnecessary web requests to the welcome page, but we can't directly copy this web request operation to the onCreate () of the startup page. We can skillfully take advantage of Activity#onWindowFocusChanged (boolean hasFocus) in the Activity lifecycle, which is the real callback after all the controls have been initialized. We can put the network operation here, and of course we can also use Service.

The above is about the content of this article on "how to optimize cold start in Android". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report