preface

Many developers work with UIs all the time and think that uIs are easy!

In fact, 90% of developers do not know the basic principles of UI.

Although in the development, we can take a shortcut to copy the large APP code after receiving the UI requirements of the product, but once the copy of the code goes wrong, it is only Baidu or guess the solution to solve.

Truly advanced engineers use other people’s code, but they have a deep understanding of advanced UI principles and performance optimization methods to avoid stutters.

I believe that you more or less read some advanced UI principles of the article, but a use of the time do not know, this article will give you clear!

Analyze UI principles from life cycle

  • Create a PhoneWindow in the Attach method of the Activity.

  • The setContentView in the onCreate method calls the setContentView method in the PhoneWindow, creating the DecorView and parsing the XML layout and adding it to the DecorView.

  • After the onResume method is executed, the ViewRootImpl is created, which is the top-level View and the parent of the DecorView. After it is created, the setView method is called.

  • The setView method of ViewRootImpl adds PhoneWindow to THE WMS, using Session as a medium. So the setView method will call requestLayout, and it will make a drawing request.

  • RequestLayout will be passed through the View’s 3 measure, layout and draw methods. The requestLayout will be passed through the View’s 3 measure, layout and draw methods.

  • Finally, use the relayoutWindow method to bind the Surface to the current Window, use the Surface lockCanvas method to get the Surface Canvas, and then draw the View through this Canvas. Finally, the unlockCanvasAndPost method of Surface is used to submit the drawn data. Finally, the drawn data is submitted to The SurfaceFlinger for screen display.

The UI optimization

UI optimization mainly includes layout optimization and view drawing optimization. What exactly is UI optimization?

Sometimes when we open a software, there will be a lag. That’s the problem with the UI. So let’s think about it, what causes a caton? Generally, it is the following:

  • The UI thread is stalled due to minor time-consuming operations.

  • The Layout is too complex to complete rendering in 16ms;

  • Too many animations are executed at the same time, resulting in excessive CPU or GPU load.

  • View is overdrawn, resulting in some pixels being drawn multiple times in the same frame time, which makes the CPU or GPU overloaded;

  • View frequently triggers measure and layout, which leads to excessive cumulative time of measure and layout and frequent re-rendering of the whole View;

  • Memory frequently triggers excessive GC (memory frequently created in the same frame), temporarily blocking the render operation;

  • Load and execution are slow due to redundant resources and logic.

  • The infamous ANR;

As you can see, the above causes of lag are very common in our daily development.

Some of you may think that your App is OK to use, but that’s because you haven’t done some transient testing and stress testing, and once you run your App in this environment you’ll find a lot of performance problems.

Here are some common UI optimization methods to share with you.

The so-called UI optimization is to take down the time spent in the rendering process, find the bottleneck and optimize it.

You’ve analyzed the UI principles, the relationship between activities, Windows, DecorView, and ViewRootImpl, and how XML layout files are parsed into View objects.

Time consuming:

  • View creation is in the main thread, including measure, layout, draw, when the interface is complex, this part may be time-consuming.
  • Parsing the XML and reflecting the time it takes to create the VIew object.

The following are some common UI optimization methods

3.1 Conventional Mode

  1. Reduce UI hierarchy, use merge, Viewstub label optimization
  2. The optimized layout overhead, RelativeLayout, and Linearlayout with weight are measured multiple times. Try using ConstraintLayout instead.
  3. When you create a DecorView, it sets a default background for the DecorView. You can use a common background for the DecorView. You don’t need to set a background for the other parent controls.

3.2 XML to code

Writing a layout with XML is convenient, but you eventually have to parse the XML out via the LayoutInflater’s inflate method and recursively + reflection to create the View object, which can be time-consuming if the layout is complex.

Using code creation reduces this part of the View creation time with XML recursive parsing and reflection. Of course, if you write all the XML in code, you’re not going to be productive, and the code readability is a problem.

Palm read open source a library, compile time automatically XML into Java code, X2C

Its principle is to use APT (Annotation Processor Tool) + JavaPoet technology to complete the operation of the whole process during compilation [Annotation] – [Annotation] -> [translate XML] -> [generate Java]

During the compilation and generation of APK, the layout that needs to be translated is translated into the corresponding Java file. In this way, the developers write the layout in the original XML, but for the program, the runtime load is the corresponding Java file.

Extremely low intrusion, and removing annotations falls back to native runtime parsing. Of course, there are cases where conversions are not supported, such as the merge tag, whose parent cannot be determined at compile time.

3.3 Creating a View asynchronously

Create View through child thread, reduce main thread time.

private void threadNewView() {
        new Thread(){
            @Override
            public void run() {

                mSplashView = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_splash,null);
            }
        }.start();
    }
Copy the code

Of course, this approach deals with synchronization issues, and it doesn’t address the time required to create the View in the first place, it just puts that time into the thread. UI updates must be switched to the main thread, otherwise the ViewRootImpl checkThread check will be triggered.

void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }
Copy the code

3.4 the reuse View

Reuse View this should be more common, like RecyclerView four cache, the purpose is to reduce the time to create a View by reuse View.

We can use the onDestroy method to clear the state of the View and put it in the cache. Hit the cache while onCreate and set the state.

3.5 Asynchronous layout: Litho

Under normal circumstances, measure, layout and draw are all executed in the main thread, and the final drawing operation is in the draw method, while measure and Layout just do some data preparation, which can be completely put into the child thread to do.

The principle of Litho is to put measure, layout in the child thread: github.com/facebook/li…

Advantages:

  1. Measure, layout, in the child thread to do, reduce the main thread time.
  2. Use your own layout engine to reduce the View hierarchy and make the interface flat.
  3. Optimize RecyclerView and improve cache hit ratio.

Disadvantages:

  1. Cannot preview in AS.
  2. Using your own layout engine has a bit of cost to use.

3.6 Flutter: Self-painted engine

Flutter is a cross-platform UI framework that integrates the Skia image library internally and takes over the image drawing process itself. The performance is as close to native as possible. It’s time to plan and learn


In the process of learning, I can quickly improve my personal level only if I am good at summarizing. Here, I also summarize a comprehensive Analysis of Android Performance Optimization, which contains 1586 pages, 5 chapters and 95 small points. It not only analyzes the detailed underlying principles, but also explores and practices of daco performance optimization!

Chapter one performance optimization experience and experience

  • The mobile performance monitoring scheme is Hertz

  • Vm tuning for Android performance optimization

  • Android UI performance optimization

  • Meitutakeout Android Lint code checking practices

  • Memory leak analysis using Android Studio and MAT……

Chapter two Response speed

  • Android App startup optimization full record

  • How to calculate App startup time in Android?

  • Application startup time

  • Alipay App construction optimization analysis

  • Redex preliminary study with Interdex: Andorid cold start optimization……

Chapter three fluency

  • Overview of frame loss causes in Android

  • A case study of the whole machine stalled due to Android barrier-free service

  • Display performance indicators

  • Slow render

  • Android fluency detection principle analysis……

Chapter 4 Memory

  • The impact of low memory on Performance in Android

  • Android OOM case study

  • Android code memory optimization recommendations

  • Android Anonymous Shared Memory (Ashmem) principle

  • Linux Check the memory consumption of processes……

Chapter five Graph stack

  • Hardware Layer in Android

  • Introduction to the principle and implementation of Android hardware acceleration

  • Overview of the Android graphics system

  • Choreographer principle

  • SurfaceFlinger start article

  • Android application UI hardware accelerated rendering technology……

There’s also “360° Performance Tuning in All Its aspects,” which has 721 pages, four chapters, and 25 dots.

1. Design ideas and code quality optimization

2. Program performance optimization

  • Startup speed and execution efficiency optimization
  • Layout detection and optimization
  • Memory optimization
  • Optimize the power consumption
  • Network transmission and data storage optimization
  • APK size optimization

3. Optimization of development efficiency

  • Distributed version control system Git
  • Automatic build system Gradle

4. Project actual combat

  • startup
  • fluency
  • Douyin in APK packet size resource optimization practices
  • Youku responsive layout technology full analysis
  • Network optimization
  • Revelation of mobile Taobao Double eleven performance optimization project
  • Autonavi APP full link source dependency analysis
  • Completely eliminate OOM experience sharing
  • Wechat Android terminal memory optimization practices

Need friends only need to support after the likes, and then [Click here to get it free】