Android performance analysis --- start Caton optimization

1. Premise

Android studio4.2.2

compileSdkVersion 30

buildToolsVersion "30.0.3"

        The startup lag in Android will cause the icon on the screen to be clicked, and the response interface will appear after waiting for a long time, or a black or white screen will appear for a long time during startup. Before optimizing, we have to analyze and find out where the freeze is, which affects the reason for our slow startup. The previous article introduced how to analyze the freeze problem during the Android development process, not limited to the start freeze. Article address: Android performance analysis --- Caton analysis_sunbinkang's blog-CSDN blog

The prerequisite for optimization is that you have to analyze those places that you can optimize, and you can find out the places that take a long time through tools.

2. Optimization --- cold start

Today, our article starts from the cold start problem to optimize.

When it comes to the startup of Android, we must roughly know the startup process so that we can find out the problem better and faster.

The startup of Activity mainly involves four processes

SystemServer process: mainly responsible for managing the entire Framework

App process: When the app user clicks the desktop icon, the Launcher process requests the SystemServer process, and then notifies Zygote to incubate.

Zygote process: All application processes are hatched by Zygote, and the Zygote process is hatched by the init process, a child process of the init process.

Launcher process: the first application process hatched by the Zygote process.

The startup of Activity mainly involves seven stages

The first stage: Launcher notifies AMS to start a new Activity (executed in the process where Launcher is located)

The second stage: AMS first checks the correctness of the Activity, and if it is correct, temporarily stores the information of the Activity. Then, AMS will notify the Launcher program to pause Activity (executed in the process where AMS is located)

The third stage: pause the Activity of the Launcher, and notify AMS that it has been paused (executed in the process where the Launcher is located)

The fourth stage: Check whether the process where the activity is located exists. If it exists, it will directly notify the process and start the Activity in the process; if it does not exist, it will call Process.start to create a new process (executed in the AMS process, internally through socket and Zygote communication, fork a new process)

The fifth stage: Create an ActivityThread instance, perform some initialization operations, and then enter the Loop cycle. (executed in the newly created app process)

The sixth stage: process the communication request sent by the new application process to complete the creation process, and notify the new application to bind the Application. If Application does not exist, LoadedApk.makeApplication will be called to create a new Application object . And notify the process to start the target Activity component (executed in the AMS process)

The seventh stage: Load the MainActivity class and call the onCreate statement cycle method (executed in the newly started app process)

        From the above startup process analysis, we can know that the points we can start to optimize are mainly the oncreate life cycle of our application and the onCreate or onResume, onStart and other life cycles of the activity . Other processes are all Android system calls, and we generally cannot interfere.

Optimization 1. Theme switching to solve the problem of black and white screen

        When the system loads and starts the App, it takes a corresponding amount of time, which will cause users to feel a "delay" when clicking the App icon. In order to solve this problem, Google's approach is to create the App . Display a blank page first, and Google configures the BackgroundWindow of the default theme with a default value of white or black , so that users can experience an immediate response after clicking the icon. If the startup process of your application or activity is too slow, resulting in the system's BackgroundWindow not being replaced in time, there will be a white or black screen at startup (depending on whether the Theme theme is Dark or Light). To eliminate the black/white screen problem at startup, most Apps solve it by setting their own background image in Theme.


Add a startup theme to styles.xml or themes.xml under the values ​​folder of res

<style name="Launcher">
    <item name="android:windowBackground">@drawable/bg</item>
</style>
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/white" />
    <item>
        <bitmap
            android:gravity="center"
            android:scaleType="centerCrop"
            android:src="@drawable/icon_qq_login" />
    </item>
</layer-list>

 

 

 

 Summary: This optimization solution is actually a palliative, not a permanent solution. It creates the illusion of fast startup from the perspective of deceiving users. But it's better than seeing a white or black screen.

Optimization 2. Use idleHandler to delay processing

The actual project found that Youmeng and Tencent TBS take a long time. While considering the business, they can be initialized after the CPU is idle, so these third-party initializations are put here.

Looper.myQueue().addIdleHandler {
    // TODO:依赖库的初始化
    false
}

IdleHandler is a callback interface, and the implementation class can be added through MessageQueue's addIdleHandler. When the tasks in the MessageQueue are temporarily processed (there is no new task or the next task is delayed), this interface will be called back at this time, and if it returns false, it will be removed, and if it returns true, it will be the next time the message is processed. Keep calling back.

Optimization 3. Layout optimization

        Reduce the nesting level of the layout, use include, viewStub, meger and other tags

Optimization 4. Asynchronous loading

        Use asynchronous threads to load some logic, you can use: RxJava, thread pool, AsyncTask, IntentService, HandlerThread, Thread

Optimization 5. Lazy loading

        For example, if the homepage is a viewpager+fragment, you can use lazy loading optimization

Optimization six, StrictMode strict mode

        StrictMode is a developer tool that detects time-consuming irrational things we might be doing unintentionally and brings them to our attention so we can fix them. StrictMode is most commonly used to capture file disk or network access on the application's main thread. Helping us keep disk and network operations off the main thread makes for a smoother, more responsive application.

Set strict mode in the application's OnCreate method.

fun setStrictMode() {
        if (BuildConfig.DEBUG) {
            //线程检测策略
            StrictMode.setThreadPolicy(
                StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads() //读、写操作
                    .detectDiskWrites()
                    .detectNetwork() // or .detectAll() for all detectable problems
                    .penaltyLog()
                    .build()
            );
            StrictMode.setVmPolicy(
                StrictMode.VmPolicy.Builder()
                    .detectLeakedSqlLiteObjects() //Sqlite对象泄露
                    .detectLeakedClosableObjects() //未关闭的Closable对象泄露
                    .penaltyLog() //违规打印日志 
                    .penaltyDeath() //违规崩溃 
                    .build()
            );
        }
    }

This can help us find out the problems better and in a timely manner, instead of finding these problems when it is to be released afterwards.

3. Summary

        Performance analysis should be analyzed and optimized according to the actual situation of the project. Performance optimization is a time-consuming process, so we should try our best to avoid these problems during the usual development process, instead of doing performance analysis and optimization when it is about to be released online, so that it takes more time than usual to pay attention Also more time-consuming and labor-intensive. Therefore, developing good development habits can help us grow better.

Guess you like

Origin blog.csdn.net/sunbinkang/article/details/125128651