For our technology practitioners, there are times when we don't know what to do, but we don't know what to do. Today the system summarizes its own experience of how to optimize Android applications, totaling eight dimensions.
1. Layout optimization Why?
Android system each 16MS issued VSync signal, triggering the UI rendering, in order to achieve a smooth interface, must implement 60FPS, it means that most of the operation must be completed in 16ms.
In addition to the above interface is too complex to render the rendering can not be completed in time, there are over-drawing problems. So-called over-plotting is a pixel that is drawn multiple times within the same frame. In a multi-layered UI interface, if the invisible UI is also being drawn, the pixels of these coincident regions are drawn multiple times. This wastes a lot of CPU and GPU resources. Over-rendering also occurs when background overlap, such as layout has its own background, while the sub-view has its own background.
How to detect?
- Use Hierarchyviewer to find out if the layout in your activity is too complex
- Open the show GPU overdraw option in developer options to see if there is over-drawing
- Select the profile GPU Rendering in the developer options and select on the screen as bar
- Use TraceView to observe CPU performance
How to optimize?
- Reduce the level of layout, reasonable use of include,merge,viewstub
- Avoid a large number of temporary objects, such as String, from being created in the OnDraw () of a custom component to prevent frequent triggering of GC
- In the custom component's OnDraw (), consider using Canvas.cliprect () to draw the area that needs to be drawn
- For a component container such as a ListView, consider using Convertview, using Viewholder,
- Consider using a higher-performance component, such as the recommended use of Recycleview instead of a ListView, and using Staticlayout for automatic line wrapping
2. Memory optimization Why?
Resources are always limited, and memory is also a resource. In Android, excessive/inappropriate use of memory resources can cause applications to be killed frequently and ultimately affect the user's overall experience. Any developer should save memory in mind.
How to detect?
- Using Leakcanary
- Analyzing the Java heap using the mat
- Use Application Tracker in Android Device Monitor to track memory allocation information
- Android Monitor in Android Studio, select the memory
How to optimize?
Active release of memory, appropriate release of memory in Onlowmemory () and Ontrimmemory ()
Avoid memory leaks and memory overflows
When using bitmap, consider compressing it, using the cache or changing the color mode, such as Android default color format is argb_8888, in the case of low requirements can be used rgb__565, so that each pixel 1 occupied memory can understand 4byte to 2byte .
Reduce the use of frame animations, if needed, through Surfaceview implementation
Use more lightweight data structures, such as Arraymap/sparsearray
Use relevant components appropriately, such as service and WebView, to proactively end their lifecycle when not needed
Reasonable use of multi-process, such as music player class, can be divided into the main process and the playback process
Consider a bounded queue when using an asynchronous queue
If you can clearly know the size of the HashMap, then set the capacity for it when initializing
?
3. Power optimization Why?
Battery power is a very valuable resource for mobile devices, and as a developer, it is necessary for users to reduce power consumption. Surveys show that only about 30% of the power is consumed by the function of the program core, such as interface rendering, the remaining 70% is reported data, location updates, background notification consumption.
How to detect?
- Phone options by viewing the app's power consumption statistics
- Use the battery Historian tool to view detailed power consumption
How to optimize?
- Reduce the number of wake-up screens and duration, using wakelock correctly.
- Delay the non-essential operation to the charging state, such as log escalation can be completed at night when charging, which can be combined with Jobscheduler
- When you use the sensor to collect data, you do not need to remember to unregister.
- Reduce network traffic and merge communications.
- Reasonable use of positioning function, reduce the location update frequency and according to the actual situation using different precision positioning requirements
4. Network optimization Why?
Now almost all apps need to be networked, so network optimization can improve the experience, on the other hand, reduce the loss of traffic and power. In addition, the network is also a resource for users and network service providers, and no developer should assume that network resources are unrestricted.
How to detect?
- Use network traffic tools in Android studio to view Web requests
- Using Monitor in Android Studio
- Analyze network packets using Fidder or Charles Grab kit tools
How to optimize?
- Be sure to cache when necessary, whether it is images or normal data, build your own cache system using LRUCache and Disklrucache, and design caching strategies based on real-world scenarios
- Avoid excessive network synchronization and merge related network requests
- The request policy is determined based on the actual scenario, avoiding the use of a fixed interval frequency for network operations. For example, when connecting to WiFi and charging, the request frequency can be high, and the first network request can be used twice for the next time.
- Reduce the amount of data transferred and compress the transmitted information. If you are transferring pictures, you need to select the appropriate picture format and request the appropriate specifications according to the size of the display. For normal data, consider using protocalbuffers to reduce the size of the transmitted data.
- In some cases, IP direct connection can be used, on the one hand can reduce the DNS resolution time, on the other hand can prevent domain hijacking
5. Start optimization Why?
Start-up optimization does not seem to be necessary, but from a psychological point of view, the faster the start-up speed often gives users a good performance, efficient and reliable psychological hint, it is easy for users to produce goodwill, for you to impress the user left room.
How to detect?
- Using method tracing
- Use Systrace, such as adding trace.beginsection () and Trace.endsection () in OnCreate
- Use to
adb shell am start -W [packageName]/[packageName.MainActivity] measure cold start time
How to optimize?
- Reduce complex and time-consuming operations in the activity's OnCreate ()
- Application's OnCreate (), Attachbasecontext () also reduces complex and time-consuming operations, but for many apps it performs initialization operations for a number of components and services here, if parallel initialization may be considered
- Provides a custom startup window, such as displaying a picture as a startup window by setting a theme.
- Optimizing layouts
6. Volume optimization Why?
For users, whether it is user space or network, or time, is a resource. Volume optimization is an important part of saving resources for users. If you are doing the SDK class now, volume optimization is just as important.
How to detect?
- Use Android Lint to check for unused resources
How to optimize?
- Reduce unnecessary reliance on the library/jar, in the premise of satisfying the need to choose small size.
- Use the Proguard tool for code slimming, optimization, confusion
- Reduce the number of so files and provide so files according to the actual situation
- Use Shrinkresource in Gradle to exclude unused code and resources from the APK installation package
- Reduce the size of picture resources, consider image compression or use Vertor drawable instead of Png/jpeg
- Choose a picture resource with the corresponding resolution
- Reuse existing images, multi-use code to transform existing images in a way that enables reuse
- Use plug-in technology (do not use if the project is simple)
7. Performance optimization
It's not bad for applications to be able to play 100% of the capacity and not just 50% of them. The same price is sold to the user two cars, I think most people will choose performance better.
How to detect?
- Perform static analysis using lint, Analysis->inspect Code in Android Studio
- Open Strictmode in Developer options or in code
- Code review
How to optimize?
- Task parallelism, parallel operation of possible tasks, multi-thread pool instead of direct use of threads
- How to serialize data, giving priority to Android itself rather than Java-provided serializable
- Select the right data structure to define the complexity of the list/set/map/stack operation
- Use Android to provide more efficient containers, such as using Arraymap instead of HashMap, plus Sparseboolmap,sparseintmap,sparselongmap
- Use static constants instead of enum types to reduce memory consumption by at least twice times
- Using object pooling techniques, such as providing a pool of objects like string
- Using caching technology
- string concatenation operation Limited use StringBuilder
- Optimize related algorithms and logic to reduce unnecessary processes
- Using JNI, the logic of the large computational volume will be its coprocessor so file, the chip processing
Business Optimisation
In addition to the above-mentioned optimizations, it should take some time to optimize the business. Many times, due to time pressure, the current solution to achieve business is not optimal. For example, to support multiple image uploads, many people use serial operations directly, although this is easy to implement, but is not optimal.
Because each product's business is not the same, it is difficult to have a general optimization solution, here are two goals worth thinking about:
- If possible, serial business parallelization
- Streamline business processes, if possible. The way to put an elephant in the freezer is to open the refrigerator, put the elephant in it, and finally close the refrigerator.
The reason why business optimization is the ultimate reason is that the risk of business optimization is high, it needs the team's overall cooperation to complete.
This color mode is delicate in color, showing the highest quality and occupying the largest memory.
- Images in Android are available in four color formats, respectively
By default ARGB_8888 , the ARGB, respectively, represent transparency, red, green, and blue, each of which is recorded with 8 bits, which means that a pixel takes up 4byte and a total of 32 bits.
This ARGB_4444 is similar to the above, but each value is recorded with 4 bits, that is, a pixel occupies 2byte, a total of 16 bits.
RGB_5655-bit, 6-bit, 5-bit to record each value, there is no transparency, each pixel will occupy 2byte, a total of 16 bits.
ALPHA_8: This pixel only preserves transparency and takes up to 1byte, a total of 8 bits.
In practical applications, values are recommended ARGB_8888 and RGB_565 , if you do not need transparency, choose RGB_565 to reduce the memory footprint by half.
Android App Optimizer mini-brochure