How to read and
Android performance optimization skills & black technology, so that your App to achieve the ultimate fluency and stability, today we mainly explain the difficulties of performance optimization and tool use.



1. Learning performance optimization analysis tools

Before you start code tuning, learn to use performance analysis tools. The following three tools are officially released by Google to help us locate and analyze problems and optimize our APP.

The System Trace,

Systrace is a tool that collects and detects time information, showing where CPU and time are being spent, and what each process and thread is doing in its CPU slice. It also indicates what went wrong and makes Fix recommendations. The resulting trace file is opened in HTML format, which is very convenient to view directly with a browser. Open method: After the DDMS is enabled, connect the mobile phone and click the SysTrace button in the upper row of the mobile phone. The opening effect is shown below:



In the code, the type is as follows:



· Hierarchy Viewer

The Hierarchy Viewer provides a visual interface to observe the Hierarchy of a layout, allowing us to optimize the Hierarchy

, remove unnecessary unnecessary View hierarchy, improve layout speed. In addition, the Debug GPU overdraw option in developer mode can also be used for view-level debugging. Open hierarchyViewer.bat in the SDK-> Tools directory. The effect is shown below:



TraceView,

A graphical tool for displaying and analyzing method execution times. It is also a performance optimization artifact. Can pass like dozen
Log is used to locate the execution time of the code, so that it can pinpoint which piece of code is taking too much time to execute. More powerful and complex to use than SysTrace.



2. Layout optimization

Layout optimization in Android mainly includes the following three aspects: layout level and measurement times, layout excessive drawing, drawing process

1. Layout level and measurement times

The more layers the layout has, the more time it takes to draw. Consider using a solution with fewer layers of layout.

(I) Reasonable selection of the parent container

When the number of layout layers is the same, we give priority to the parent container with fewer measurement times. Usually, the priority we choose is:

FrameLayout, LinearLayuut without Layou_wight, RelativeLayout. Because the LinearLayout and RelativeLayout with Layot_weight measure twice.

In summary, the scheme with fewer layout levels should be given priority first, and the scheme with fewer measurement times should be adopted when the layout levels are the same.

So how do you analyze the layout hierarchy?

(1) Android Device Monitor

Starting from Android Studio3.0, Google does not recommend using it, so we need to manually find it in tools under the SDK directory, then run your APK and select Hierarchy View to View the corresponding Hierarchy, as follows:

(2) Component Tree

After Android Studio.3.0, we can use the Component Tree, which also provides the ability to view the Component hierarchy as follows:



Select and view our XM layout and click On Design in the lower left to see the left hierarchy.

(2) Labels

In addition to the methods mentioned above, we can use tags to reduce hierarchy and reuse components

(1) Include tag

The purpose of the include tag is to refer directly to an existing layout without having to rewrite it. Instead, include is usually used in conjunction with the merge tag, which is described below.

Such as:

Include refers to a Linear Layout. We don’t need to repeat the Layout, but it adds a hierarchy.

(2) Merge tags

The merge tag is usually used as an extension of the include tag to solve the problem of increasing the layout level caused by the introduction of include. After the merge tag is used, the View in the merged layout becomes the child View of the parent layout. As follows:





With the include tag, the hierarchy is as follows:



Now we change the label to merge, and the hierarchy is as follows:



You can see that there’s a layer missing in the middle.

(3) ViewStub tag

The ViewStub, which inherits from the View, is a lightweight, zero-width and zero-height component that does not itself participate in layout and drawing. Therefore, it can be used to not load when it is not needed and load when it is needed, thus improving performance. So how to do when you need to display?

You can use the following two methods:

setVisiable

“(unavailable.Visiable) or
findViewById().inflate()

(3) Use Constaint Layout

Constaint Layout allows you to create complex layouts without using any nesting, and Relative Layout

Similarly, you can rely on the relative relationship between the sibling container and the parent control. Common attributes:

app:layout_constraintLeft_toLeftOf=”parent”

app:layout_constraintTop_toTopOf=”parent”

app:layout_constraintLeft_toRightOf=”@+id/iv_image”

Such as:





2. Overdraw

Overdrawing is when a pixel on the screen is drawn multiple times in the same frame.

In a multi-level overlapping UI structure, if the invisible UI is also being drawn, some pixel areas will be drawn multiple times, wasting a lot of CPU and GPU resources. There are currently two ways to detect overdrawing:

There is a debug GPU Overdraw > Show GPU in the developer mode of the phone
Overdraw, after setting, open any APP, you can see one or more of the four colors blue, green, pink and red appear on the interface.

Blue: 1 overdraw

Green: 2 overdraws

Fan: 3 overdraws

Red: 4 overdraws

Such as:



, the Android device monitor

Open Hierarchy Viewer (/’haɪ rɑːkɪ/), run the emulator, and open the corresponding Activity interface. You can see the following:

In each View, the following three points indicate the measurement, layout, and drawing time in sequence. Red and yellow points indicate slow speed, while blue and green points are relatively better.

Now that we know how to analyze overdrawing, how do we deal with overdrawing?

(1) Remove the default Windwo background

Generally speaking, the activities we use will have some default theme, usually this theme will have a corresponding background, by
The DecoreView holds, and when we customize the layout and add a background image or set the background color, it generates one
Overdraw, so consider removing the default background. We can do this in onCreate () setContentView
Before calling getWindow ().setBackgroundDrawable (null) or theme
Add windowbackground = “null”

(2) Remove other unnecessary backgrounds

Sometimes we create a background for a layout that has a background for its child views. So in this case, we first think about whether we need to add a background, and if we do, we can think about using selector to make the background transparent in the normal state, and then setting the background in the click state to reduce redrawing.

(3) Optimize onDraw method

Avoid assigning objects in the onDraw () method, because the onDraw method can be called multiple times, which can create a lot of unnecessary objects. Use ClipRect to specify a drawing area. When using a custom View, we can use this method to specify one visible area for drawing and the other areas are ignored. That is, only the region specified by clipRect is drawn. For example, when the image is stacked, we will not draw the overlap, only draw the non-overlap. Draw directly as follows:

You can see that the overlaps are overdrawn, and in fact we don’t need to draw the bottom part of the overlaps because we can only see the top layer, so we can specify the region using clipRect (). As follows:

(4) Tags include, merge, viewStub tags mentioned earlier

3. Thread optimization

1. The View cannot be operated on by non-UI threads. Because Android’s UI is not secure, if the View can be accessed or modified by different threads, unexpected behavior or concurrent errors can occur during application execution.

2. When using threads, avoid using synchronization in round-tripping because the operation of acquiring and releasing locks is expensive. CPU resources are consumed.

3. When handling multithreading and interthread communication, use HandlerThread, which has Looper wrapped inside, to exit/release resources when not in use.

4. It is recommended to use AsyncTask when communicating between the worker thread and the UI thread (after Android 7.0, internal tasks become serial processing, which will no longer occur when the number of concurrent tasks exceeds the saturation strategy)

5. Loader can be used instead of AsyncTask in some cases, because the Loader life cycle is independent (related to the Application Context), it is still alive when the Activity/Fragment is destroyed and rebuilt, and it specifically uses asynchronous operations. For example, AsyncTaskLoader can replace AsyncTask to realize the latter function, but its life cycle is completely independent of Activity. Remember to destroy Loader after use.

6. When your Service does not need to interact, use an automatic stop IntentService.

7. When you want to extend the life of the BroadcastReceiver, for example, start a background thread, IntentService. OnReceiver invokes the BroadcastReceiver. GoAsync (), it returns a PendingResult object, at this point, the radio receiver will extend to the life cycle of continued to PendingResult. The finish () method call.

8. It’s best to manually create the thread pool by using the constructor instead of using Executors to invoke the factory method. If you use the wrong thread pool, avoid resource depletion.

9. Give the thread a nice name for debugging.

10. Thread pool Sets the thread lifetime to ensure accurate release of idle threads.

4. Memory leaks

In layman’s terms, a memory leak is an object that should be recycled but for some reason cannot be recycled.We all know that objects have a life cycle, from life to death, when the object’s task is completed, the Android system will do the garbage collection. As we know, the memory allocated by Android system for an App is limited (this may vary depending on the model). When a large number of memory leaks occur in an App, it is inevitable that the memory required by the App will exceed the memory quota allocated by the system, and eventually OOM(OutOfMemory) will crash the App.

5. Algorithm optimization

There are many kinds of search algorithms: basic search, binary search, binary tree, Fibonacci, etc., their time complexity and space complexity are different, choose the suitable algorithm twice the result with half the effort. For example, if there are n data in a sequential queue, the time complexity of basic search is O(n), while the time complexity of binary search is O(log 2 N). Obviously, the larger n is, the longer the basic search takes and the higher the performance loss. For example, to query a file, you can use basic search, or you can sort first and then do binary search.

6. Other optimization points

Asynchronously process time-consuming tasks

In initialization methods such as Activity and Fragemnt’s onCreate, performing time-consuming operations (such as reading various data) can slow down the page load and make the APP feel slow to the user. These time-consuming tasks can be handled asynchronously, reducing the burden of application startup.

Substitution vector diagram

Despite the advantages of vector graphics, drawing vector graphics is performance-consuming. In the areas that affect user experience, such as initial loading of applications, Bitmap is still recommended to replace vector map to improve APP startup efficiency.

Regular expression

Regular expressions are time consuming, as you can see from your constant use of TraceView. So while regular expressions are very elegant, when it comes to performance, you can use other judgment methods to improve your APP’s performance.

Floating point types

Floating-point operations in Java are about twice as slow as integer data, so use them for any problems that integer data can solve.

Reduce redundant

Log Logs used for debugging during development should be deleted in time when the project is launched. Of course, useful logs should be left for later analysis.

Deleting Unnecessary Resources

Unused resources will increase the SIZE of APK, since it is no longer used, it should be deleted in time when online.

Lint Code checking Using static code checking tools such as Lint can help us find many hidden problems. The fewer problems Lint checks, the more formal the code, the less likely it is to have various problems, and the APP performance will naturally improve.

Global broadcast abuse

Global broadcasting is also a performance drain. For in-application communication, interface callbacks, EventBus, etc. are a better choice than broadcasting. When registering broadcasts dynamically, don’t forget to unregister broadcasts.

7,

Good Android performance optimization difficulties and tools to use the first introduction here, if you think there is worth improving, please give me a message. Will inquire seriously, correct inadequacy. thank you The article mentioned in the master performance systematic construction scheme, performance analysis and optimization ideas and optimization scheme, master stability guarantee scheme, master performance optimization black technology and common scheme improvement and other common information interested in can pay attention to the forward comments
【 material 】To obtain.