Objective
The new needs of the company finally solved, away from the test and release there is a period of time, the first experience of the next no need no bug feeling, really refreshing ~ and then turned over what can be learned. Inadvertently turned to the five major trends in Android's late development. First, performance optimization. Second, advanced UI. Third, JNI/NDK development. Iv. the architect. Five, RN development. This is probably going to be my advanced trend. Already know in the bottleneck period of me, seems to see the breakthrough of Hope. Junior advanced Intermediate or intermediate level, the current market is nothing more than according to experience, according to the ability of less.
In fact, the attention of my or in the group of small partners also know that the UI that piece of my problem is not very big. But the advanced UI is difficult. We don't care about him first, one by one. First, from performance optimization. Actually, I refused to write this article. Why? Performance optimization of the classification of a lot, a classification to write a sense of space is very small, combined to write there is a great feeling. And I'm going to tidy up the whole now.
Then we analyze the performance optimization has those several aspects: first, memory optimization. Second, UI optimization (layout optimization and drawing optimization). Third, speed optimization (thread optimization/network optimization). Four, the power optimization. Five, start optimization. That should be it. So it's just five things, and it's a combination of details. No hurry, we introduce each of the following.
Memory optimized
About performance optimizations we can not know the other, but be sure to know the memory optimization. Because memory leaks can be Android's regulars. So what is a memory leak? Memory is not within the control of the GC. So what is the GC memory recovery mechanism for Java? An object is not recycled until it has any references. So what is the principle of GC recovery? Or what is the point of reference that can be used as GC root? Maybe someone can't understand what I'm talking about. Let's take a look at the picture first.
When we look up and look for the GC root, this object is not recycled, for example, an activity. So if we look up until we find the GC root object, it means it's not recyclable, for example, I've defined an int a, but this data is not used for my entire page or for the entire project, then this object will be dropped by GC.
GC's Reference point
- Objects referenced in the Java stack
- Object that the method statically references
- Object referenced by the method constant
- Objects referenced by JNI in native
- thread--"Alive" thread
How to judge
So how do we tell if an object is a garbage object that he can recycle? Give a small example to teach you how to differentiate:
一般在学校吃饭,我们有两种情况,第一:吃完饭就直接走人,碗筷留给阿姨来收拾处理。第二:吃完之后把碗筷放到收盘处直接进行回收。但我们是个有素质的人,一般采用第二种情况,但根据想法,我们更倾向于第一种。那么一般在饭店或者KFC中,都是第一种情况。那么此时,问题来了,如果我已经吃完饭,然后我并没有离开饭店,做在位置上和朋友吹吹牛逼,谈谈理想,聊聊人生。那么桌上那一堆碗筷是收还是不收?讲道理是不能收的。虽然实际也是不能收的。因为顾客是上帝~~~
So, how can we tell if an object is a recyclable garbage object? This is one of our subjective judgments. But there is a situation we have to consider, yes, too much memory can not be released, will directly lead to Oom. The whole project boom blew up. What the heck? OutOfMemory Yes, that's it.
Memory Overflow Analysis Reason
We need to analyze the cause of the memory overflow, let's take a look at a diagram:
Memory leaks generally lead to application lag, and extreme situations can lead to project boom. Boom is due to exceeding the memory threshold.
There are two main reasons for this:
- There is a leak in the code, memory is not released in time causing oom (this we say later)
- Some logic consumes a lot of memory, cannot be released in time or exceeds the cause of oom
The vast majority of the so-called consumption of memory is due to picture loading. This is the most frequent occurrence of our oom. I have written in front of the image loading method, one is to control the number of each load, and the second, to ensure that each time the slide is not loaded, the slide is finished loading. The general use of advanced after-out, rather than first-out. In general, however, our image loading is using open source libraries such as fresco or glide.
Let's look at the following two pictures:
Comparing the two graphs, we can have the oom situation in the first case, we found through the log print, processing seems to be no problem, in other words, if I do not put the 0.8M picture. And then continue to operate the same will happen to Oom, but we are blindfolded. There's no picture loading.
How to view
First, we determine whether there is a memory overflow problem in our project or in a few classes. We can use the following methods:
- Android–>system Information–>memoryusage See if there are no free views and activity in object
- Command line mode: ADB shell Dumpsys meminfo package name-D
Let me give you an example of our project. First, we can see the memory here. Usage of CPU and net.
We found object. Look at the consumption of our memory.
Take a look at it, the egg, about 1300 of the view and an activity. There are 3 other context. Terrible.. Can be understood as an activity within the use of nearly 1300 view ... I can't even think about it.
We can do this by looking at the memory Monitor tool. Check for a single action. (such as an activity jump). Perform one operation over and over again to see the approximate change of memory through this tool. Before and after two memory changes increased a lot.
We can look more closely at the location of the leak and use the heap snapshot tool (a stack snapshot) inside as. :
After we click, he will monitor for a period of time and then generate a file. We click on our package tree view.
We found the package name of our project. Then further analysis is carried out. First look at what the column names of the 2 lists mean.
To instantiate the object in more detail:
Let's take a look at the amount in memory:
This is still the first time we have entered the cell phone, a bean has been called so many times. It's horrible. We can solve this by means of memory analysis tools.
Memory analysis Tools
Performance optimization Tools:
- Heap Snapshot Tools
- Heap Viewer Tool
- Leakcanary Tools
- Mat Tool
- TraceView Tools (Device Monitor)
Third-party analysis tools:
- Memoryanalyzer
- GT Home
- ITest
Because I don't have these tools, I can't make a presentation.
Precautions
We try not to use the context of the activity, but instead use the context of the application because the lifetime of the application is long and the process exits without being destroyed. Therefore, Singleton mode is the most likely to cause memory overflow, because the life cycle of the singleton pattern should be as long as the application life cycle, rather than the same as the activity.
Animation can also cause memory overflow, why? Because we are demonstrating through view, the view is held by the activity and the activity holds the view. Finally, because activity cannot be released, it causes a memory leak. The workaround is to stop by calling Animation.cancle () in the activity's Ondestory () method, and of course some simple animations can be solved by customizing the view. At least I'm using animation very little now. No animation is a custom view that cannot be resolved. How to have, that is two ~ ~ ~.
UI optimization
UI optimization mainly includes layout optimization and view drawing optimization. No hurry, we look at the next one slowly ~ ~. First, what is the optimization of the UI? There are times when we open a software and we have a lag. This is the problem with the UI. So let's think about what's going to be the cause of the lag. In general, there are several situations:
Incurring the UI line by artificially taking a slightly time-consuming action in the UI thread;
Layout layouts are too complex to render within 16ms;
Excessive number of animations performed at the same time, resulting in excessive CPU or GPU load;
View over-drawing, which causes some pixels to be drawn multiple times within the same frame time, which can overload the CPU or GPU;
View frequent trigger measure, layout, resulting in measure, layout accumulated time-consuming and the whole view of the frequent re-rendering;
Memory frequently triggers too many GC (memory is frequently created in the same frame), causing temporary blocking of rendering operations;
Redundant resources and logic lead to slow loading and execution;
The infamous ANR;
It can be seen that these causes of the lag are very common in our development. Some people may feel that their application is quite OK, in fact, it is because you did not carry out some instantaneous testing and stress testing, once you run your app in this environment you will find a lot of performance problems.
Layout-Optimized GPU drawing
Our optimizations for UI performance can also be analyzed using the GPU over-drawing tool in developer options. Debug GPU Over-drawing (different device possible locations or different names) in Setup, developer options, can be seen after debugging (analysis of settings current interface over-rendering):
The picture looks too messy, let's take a simple picture:
Our goal is to minimize the red overdraw and see more blue areas.
Can be found, after opening in the application we want to debug the interface can see a variety of color areas, the meaning of the following:
Overdraw sometimes because there are a lot of overlapping parts in your UI layout, or because you don't have to overlap the background. For example, an activity has a background, and then the layout has its own background, and the sub-view has its own background. Simply by removing the necessary background image, this can reduce the number of red overdraw areas and increase the percentage of the blue area. This measure can significantly improve program performance.
If both Realtivelayout and linearlayout are used in the layout, use LinearLayout directly, because the layout of relativelayout is more complex, and it takes more CPU time to draw. If more than one linearlayout or framelayout nesting is required, then relativelayout can be used. Because multiple layers of nesting result in most of the layout drawing being duplicated, this reduces the performance of the program.
GPU Rendering Mode Analysis
We still open the Set –> Developer option –>GPU Rendering mode analysis –> displayed as a bar chart on the screen:
Of course, you can also enter the following command line to view the GPU-rendered data on the command line after the UI swipe operation (analysis by: Draw + Process + Execute = Full display one frame time < 16ms):
adbshelldumpsysgfxinfo[应用包名]
As the interface refreshes, the rendering time of each frame is displayed in a real-time histogram, and the higher the histogram indicates the longer the rendering time, each histogram has a green horizontal line representing the 16ms datum, and each vertical bar contains three parts (blue represents the time to measure the display list. Red represents the time it takes for OpenGL to render the display list, and yellow represents the time that the CPU waits for GPU processing, so as long as we have less than a baseline for the total time of each frame, there is no problem with the UI, which is not really the case with the baseline. Simply look at our company when the project was just started:
Suddenly there is a feeling of wanting to spit the groove ... I remember that I did a slimming optimization before, but to let me do the performance optimization, I think it should not be so simple ...
Code optimization
Both Android Studio and Intellj Idead have their own code-checking tools. Open Analyze->run Inspection by name...–>unused resource Click to start detection, wait for a moment, you will find the following results:
We can also do this, put the mouse in the code area right-click->analyze->inspect code–> Interface Select the module you want to detect, click Confirm to start detection, wait for a moment, you will find the following results:
Of course, I'm just intercepting a little bit, let's look at the following tip: @param v tag description is missing. means that the type of V is missing, either by the introduction or by deleting it directly.
The above two methods are the easiest place to find code flaws and useless code. So indulge in the pit to pits ~ ~ ~
Drawing optimization
So what is drawing optimization? Drawing optimization means that the OnDraw method of the view needs to avoid performing a large number of operations. I will be divided into 2 areas.
- The OnDraw method does not need to create a new local object, because the OnDraw method is executed in real time, so that the product will have a large number of temporary objects, resulting in more memory being consumed and the system continually being GC. Reduce the efficiency of execution.
- The OnDraw method does not need to perform time-consuming operations and uses less loops in the OnDraw method because the loop consumes CPU time. Causes the drawing to be not smooth, stutter and so on. Google officials point out that the frame rate of view is stable at 60dps, which requires that the drawing time per frame should not exceed 16ms (1000/60). Although it is difficult to guarantee, we need to reduce it as much as possible.
60dps is currently the most appropriate image display speed, but also the majority of Android device settings debugging frequency, if the interface refresh within 16ms can display a smooth screen, and for any reason to receive the vsync signal is unable to complete the refresh operation, will produce the phenomenon of frame, the refresh frame rate will naturally fall (assuming that the refresh frame rate from the normal 60fps to 30fps, the user will obviously feel the lag). So, we talked about this in front of the GPU. In general, the feeling is quite important .....
Network optimization
Threading is an essential part of our project because most of our data is obtained from the web. So, thread this is a must-have supplies.
We can still monitor the network through the following net memory:
ANR problem
I believe that this problem is not met in many of the present, then what is ANR? Application not responding. The application is not responding. So when does the general ANR appear. Android Official Rules: Activity if no response event (screen touch event or keyboard input event) within 5s. Broadcastreceiver If the completion is not processed within 10s. Service cannot be processed within 20s. These three situations can lead to ANR. Introduce the paper with a concise diagram. It looks convenient ~ ~
Threading optimization
The three types of cases that lead to ANR are mostly caused by thread blocking. So what should we do with it? The Android system provides us with several sets of tool classes to solve this problem.
Asynctask: Provides a simple and convenient mechanism for switching between UI threads and worker threads for quick processing. For scenarios where immediate start-up is needed now, but the life cycle of asynchronous execution is short.
Handlerthread: Sets a dedicated thread for some callback methods or waits for execution of certain execution tasks, and provides a scheduling mechanism for thread tasks.
ThreadPool: Splitting tasks into different units, distributing them to different threads, and concurrently processing them concurrently.
intentservice: Suitable for performing background tasks triggered by the UI. These tasks can be fed back to the UI through some mechanism.
A time-consuming network request can create a product experience that is slow for users, although it is possible to use loading to enhance the user experience, but it is a palliative. For example, when the network is poor, our company's project a loading is more than 10 s. Even more ... I remember the time I went to the interview before the project of our company, because of the problem of the net difference ... A loading for more than a minute. At that time the impulse to hit the phone has been, don't say unloading software ....
The general multithreading situation we can deal with by Asynctask. (This thing I really didn't use--) I said annotation before. This is Google's official introduction of the note. Much more powerful than bufferknife. This is quick and easy to handle multithreading and does not cause threads to block, and you can control the order of threads, for example, after I execute thread A, I execute thread B according to a parameter of thread A. And so on .....
As for the thread pool, the most is to say that the picture loaded ~ ~. Picture loading with three parties on the line ~ want to see detailed introduction, I have said before, of course, in addition to this there are download operations. This is connected with the Intentservice. General downloads I seldom relate to: Used a few times Android native Downloadmanager. Feel a little pit.
Ko Network optimization
Now I'm talking about the focus of network optimization ... Focus.. What is the most important thing in the Web? Time!! Speed!! Success!! Time!! Speed!! Success!! Time!! Speed!! Success!! Important thing to say three times ha.
Image processing
This is not the first time that a picture has been mentioned in this article. The importance of visible pictures!!
- Using the WEBP format, the same photos, using the WEBP format can greatly save traffic, compared to JPG format picture, the traffic can save nearly 25% to 35, compared to the PNG format picture, the traffic can save nearly 80%. The most important thing is that the image quality has not changed after using WEBP. So, go to the backstage with the small friends to discuss it ~ ~ ~
- Using thumbnails, I wrote the picture in front of the loading has said that is to control his inside and option. Then zoom the picture. Compression? I don't know how to compress network pictures, but I will scale ah ~ ~ Anyway, it will not be distorted. Cheer Up ~ Bite me?
Network request Processing
We can cache the service-side return data, set the effective time, not to take the network request within the effective time, reduce the traffic consumption. The cache for the network can be found in Httpresponsecache.
In some cases, we try to use GPS as little as possible, and if conditions permit, use the network location.
Download, upload, we use breakpoints as far as possible, say a simple, I am in the company, ready for the next 500M game, but the next to 200M when I work, there is no wireless network, we can go home after the wireless continue to download. So, breakpoint continuation, breakpoint download is also our compulsory course ~, so I mentioned in front of a separate article on the continuation of the breakpoint.
When refreshing the data, use local refresh as much as possible instead of global refresh, first, the interface will splash screen, the interface of the network poor directly white screen a period of time is not impossible. Second, the use of traffic!! I'm going to have to get on with our company project again. A splash screen cache 60+m ... Yes, that's 60+m. It's horrible, I clear a 3, 5 times the cache, open a 3, 5 times. OK, 2 minutes, I have no traffic for one months ... So, the network cache I mentioned earlier is very important, as to whether it will be added to the project, I still have to look at the saying-a careless, the whole project can be blown up ...
Start optimization
As we all know, a good product, in addition to powerful, good performance is also essential. Survey shows that nearly 50% of respondents because the APK is too large to refuse to use, nearly 40% of respondents due to poor app performance and uninstall, performance is the biggest cause of frustration for app users.
There are three ways to start the Android app: Cold start, warm start, hot start, and different startup modes determine how long the application UI will take to make the user visible. As the name implies, cold start consumes the longest time. The optimization based on cold start mode is also the most testing place for the product user experience. Before we talk about optimizations, let's take a look at the three startup scenarios and what the system does during startup.
Cold start
Why cold start is the longest time. Cold start is the system does not get the activity, service, etc. of the current app before starting the app. For example, start the app for the first time. Or, for the first time after the kill process is started. Then there are two other ways of comparing it. Cold start nature is the most time-consuming.
When the application is cold-started, the system must perform the following three tasks:
- Start loading and launching the app
- After the app launches, a blank startup window is displayed (splash screen splash page)
- Create app Information
Then, to create the application information, the system needs to do an arse:
- Initialization of the application
- Start the UI thread
- Create activity
- Import views (inflate view)
- Calculate View size (onmesure view)
- Get the View layout (OnLayout view)
- Drawing Views (OnDraw view)
There are two creation working, application and Activity creation respectively. They were all before the View was drawn. So, the more things the OnCreate () method does in applying a custom application class and the first Activity class, the longer the cold start consumes.
Warm start
When the activities in the app is destroyed, but it is resident in memory, the startup of the app changes to warm boot. Compared to cold start, the warm START process reduces object initialization, layout loading, and so on, with a shorter start-up time. At startup, however, the splash screen is still displayed until the content of the first Activity is rendered.
Hot start
Compared to warm start-up, the application does less work and has a shorter start-up time when hot-start. Hot start is a lot of scenarios, such as: The user uses the return key to exit the app, and then immediately restarts the app.
How to optimize
Let's compare the three startup time comparisons:
Cold start:
Warm start:
Hot start:
We can see the obvious gap between the three, a cold start for almost a minute, anyway I do not want to see, every run the project is very slow ~ so what should we do? See some people talk about changing the theme of the project. Change it into a launcher theme. But I think this is a really fine test. However, the general project will have a splash screen page. Then jump from the splash screen to the homepage. We can follow the majority of the project to improve. How to say, we can see the general items have a countdown display. That is, the countdown ends automatically into the home page. Or you can skip directly to the homepage. That means we can do it this way, that is, as long as his countdown is over, we go directly to the home page, regardless of whether the request is complete or not. We can do some necessary loading on the splash screen, such as user information, positioning and so on, so as for the other, we can go to the homepage to pre-load. As with the hot update, silently update the bug without the user's knowledge. So, for some network requests, such as ads. We can pre-load this method.
We can also, splash screen page We put him as a fragment nested in the mainactivity, then we can go to the splash screen directly preloaded page view. Countdown We remove the splash screen page directly to display the homepage.
Through the above introduction, we have a certain understanding of the start-up optimization, in fact, the summary is very simple. is to reduce the time-consuming operation, summarized as follows:
- The main thread involves whether Shareperference can be executed in a non-UI thread.
- Application the creation process with minimal time-consuming operations.
- Reduce the level of layout and minimize time-consuming operations in the method of life cycle callbacks.
Power optimization
With UI optimization, memory optimization, code optimization, and network optimization, we're talking about an important optimization module in application development--power optimization.
Power consumption concept
In fact, most developers are very low on power optimization, in fact, it is mentioned that performance optimization is the memory optimization, but we can not ignore the other optimization, power optimization is actually necessary, such as Iqiyi, Youku and so on video player and music player. As we all know, music and video are actually the biggest power consumption. If users find that our application is very power hungry, I'm sorry, most of them will choose Uninstall to solve this kind of problem. To do this, we need to optimize.
How to optimize
In fact, we have the above four kinds of optimization solved, is the best power optimization. So, for power optimization, here are some suggestions:
- When a network request is required, we need to determine the current state of the network.
- In the case of multi-network requests, it is best to do batch processing to avoid frequent interval network requests.
- In the case of both WiFi and mobile data, we should direct the screen to move the data of the network request, only when the WiFi is disconnected in the call, because the WiFi request power consumption is much lower than the power consumption of mobile data.
- Background tasks to wake up the CPU as little as possible. (for example, when the lock screen, QQ message prompt line is to wake up the CPU.) But it only prompts you when you turn on the lock screen or charge it. )
Optimization Summary
Performance optimization is our way to advanced. So, we have to be, as for the "will" to what extent, it depends on personal understanding. In fact, the above is only a performance problem of the iceberg, the real optimization, we are in the project summed up. But, we can not blindly pursue optimization, for example I, now just in the summary of optimization, and for the real implementation, and did not start, because, optimization is risky, an careless, the whole project can be blown up. So this requires your experience, as well as a variety of summaries, to be optimized in place of optimization to see how it works, such as UI optimization and code optimization. You can take some of the online open source projects to optimize and so on. Finally, enjoy the optimization of the best ~ ~ ~
Article reference
"Android Art Quest"
Full analytics for Android app development performance optimization
Performance Optimization Model
Dual 12 Technology Brother
Google's official optimized video
Full-aspect analysis of Android performance optimization