Android App Performance Optimization (latest summary)

Source: Internet
Author: User

LeadThe Great Army of Android, the development of nearly ten years, technology optimization day to month new, now Android 8.0 Oreo are released, Android system performance has been very smooth. However, to the major manufacturers in hand, to change the source system, so that the Android native system has become a mixed bag, and then to the different levels of development engineers, because of uneven technical level, even if many mobile phones in running sub-software performance is very high, open applications still lag phenomenon. In addition, with the product content iteration, the function is more and more complex, the UI page is also more and more rich, also become a smooth operation of a hindrance. To sum up, the performance optimization of the app has become a comprehensive quality for developers and a guarantee for developers to complete high-quality application work. Thinking optimizationIn the humanitarian, all from the perspective of user experience, when we put ourselves as a user to play an application, then what will care? If you are playing a hand tour, first of all, you do not want to play a sudden flash back, and then encounter the picture content is very rich when do not want to lag, the second is the power consumption and consumption of traffic do not want too serious, and finally is the version of the update when the installation package hope to be smaller. Well, the four aspects are summarized as follows:
    1. Stable (memory overflow, crash)
    2. Smooth (lag)
    3. Wear (power consumption, flow)
    4. Install package (APK slimming)
First, stability-memory optimization due to the sandbox mechanism of Android application, the memory size allocated by each application is limited, the memory is too must not will trigger Lmk--low memory killer mechanism, there will be a flicker phenomenon. First understand how the Java memory is allocated and recycled, the problem is solved. Related articles:

Java garbage Collector's GC mechanism, see this one is enoughAndroid Memory Leaks common cases and analysisOnce you know how memory is allocated and how the memory is recycled, you have a little bit of knowledge and mastery of memory optimization.

Using analysis tools

    • Memory Monitor Tool:
It is a memory monitoring tool that comes with Android studio, which helps us to do real-time analysis of memory. By tapping the Memory Monitor tab in the lower right corner of Android studio, you can open the tool to see that the lighter blue represents free RAM, while the dark part represents the memory transformation from the memory transform, which can be used to determine the state of memory usage, for example, when memory is continuously increasing, A memory leak can occur, and a GC can occur when memory suddenly decreases.

    • Memory Analyzer Tool:

MAT is a fast, feature-rich Java Heap Analysis tool that analyzes the memory snapshot HPROF analysis of Java processes, analyzes from numerous objects, quickly calculates the size of objects in memory, and views which objects cannot be reclaimed by the garbage collector. You can visually view the objects that may be causing the result through the view.

    • Leakcanary Tools:
Simple, fool-type operation. This tool is open source on GitHub, is produced by the Square company, not a word, square produced must be a boutique, https://github.com/square/leakcanary we can quote it in Gradle.
    • Android Lint Tools:
Android Sutido is an integrated Android code hinting tool that can give you a very powerful help with layout and code. If you write a three-layer redundant linearlayout layout in the layout file, you'll see a hint on the right side of the editor. Of course, this is a simple example, lint function is very powerful, we should form a code to see the habit of lint, which not only allows you to find the code in time to hide some of the problems, but also allow you to form a good code style, you know, These lint tips can be Google Daniel Sweat and wisdom of the crystallization.

Stability recommendations affect the stability of a lot of reasons, such as the unreasonable use of memory, the code anomaly scenario is ill-conceived, code logic unreasonable, etc., will affect the stability of the application. The two most common scenarios are: Crash and ANR, both of which will make the program unusable. So do a good job of crash monitoring, the collapse of information, the collection of abnormal information for subsequent analysis; reasonable use of the main thread processing business, do not take time-consuming operation in the main thread, to prevent the ANR program no response occurs. Second, fluency-Interactive optimization interaction is the most direct aspect of user experience, the interaction scenario is divided into four parts: UI drawing, Application launch, page jump, event response, four aspects are roughly classified as the following two categories:
    • Interface drawing: The main reason is the depth of the drawing layer, the page is complex, the refresh is unreasonable, because of these causes the stutter scene more in the UI and after the start of the initial interface and jump to the drawing of the page.

    • Data processing: The cause of this stalling scenario is the data processing volume is too large, generally divided into three cases, one is the data in the processing UI thread, the second is the processing of high CPU, resulting in the main thread can not get the time slice, three is the memory increase caused by GC frequent, resulting in the card Dayton.

Summary reason: We know that the drawing steps of Android are: Measure, layout, www.365soke.cn draw, so the deeper the level of layout, the more elements, the longer the time. There is the Android system every 16ms issued a VSYNC signal, triggering the UI rendering, if every time the rendering is successful, so that the smooth screen to achieve the required 60FPS. If the time spent on an operation is 24ms, the system will not normally render normally when the VSYNC signal is obtained, so the drop frame phenomenon occurs. Then the user sees in the 32ms will be the same frame screen, unable to complete the rendering at 16ms, resulting in a refresh is not timely. Two root causes:

    1. Drawing a task is too heavy, it takes too long to draw a frame.

    2. The main thread is too busy, according to the system passed the VSYNC signal came when the data is not ready to cause dropped frames.

Recommendation 1: Layout optimizationwhen a view is measured, laid out, and drawn on the Android system, it is manipulated by traversing the view number. If the height of a view number is too high, it can seriously affect the speed of measurement, layout, and drawing. Google also suggested in its API documentation that the view height should not be more than 10 layers. Now the version of Google uses relativelayout instead of Lineralayout as the default root layout to reduce the height of the lineralayout nesting to produce the layout tree, thus improving the efficiency of UI rendering.
    • Layout reuse, reusing layout with <www.taohuayuan178.com include> tags;
    • Improve display speed, use <ViewStub> delay view load;
    • Reduce levels and replace parent layouts with <merge> tags;
    • Pay attention to the use of wrap_content, will increase the measure calculation cost;

    • Delete the unused property in the control;

Recommendation 2: Drawing optimizationsover-drawing means that a pixel on the screen is drawn several times within the same frame. In a multi-layered UI structure, if the invisible UI is also drawing, it causes some pixel regions to be drawn multiple times, wasting redundant CPU and GPU resources. So avoid over-drawing:
    • Optimization on the layout. Remove the required background from the XML, remove the Window's default background, display a placeholder background image on demand

    • Custom View optimization. Use Canvas.cliprect () to help the system identify those areas that are visible and will be drawn only within this area.

Recommendation 3: Start optimization

UI layout. Apps typically have splash screens that optimize the UI layout of the splash screen and can detect dropped frames through the profile GPU Rendering.

Initiates load logic optimizations. You can use distributed loading, asynchronous loading, and deferred loading strategies to improve application startup speed.

Data preparation. Data initialization analysis, loading data can be considered with thread initialization and other policies.

Recommendation 4: Refresh Optimizations
    • Reduce the number of refreshes;
    • Reduce the refresh area;
Recommendation 5: Animation optimization
    • When animating, it is necessary to choose the appropriate animation frame for different scenes. In some cases, you can use hardware acceleration to provide smoothness.
Three, saving--power consumption optimization

In mobile devices, the importance of batteries is self-evident, without electricity, nothing can be done. For operating system and device developers, power consumption optimization does not stop, to pursue longer standby time, and for an application, it is not possible to ignore the use of electricity, especially those classified as "battery killer" application, the end result is uninstalled. As a result, application developers need to minimize power consumption while implementing requirements.

Before Android5.0, it was cumbersome and inaccurate to test the power consumption in the application, and after 5.0, a api:battery Historian was introduced specifically to obtain information about the power consumption on the device. Battery Historian is a Google-provided Android power analysis tool that, like www.boshenyl.cn Systrace, is a graphical data analysis tool that visually shows the power consumption process of your phone. By entering a power analysis file, display consumption, and finally provide some methods to optimize the reference power.

In addition to this, there are a few common options available:

    • Calculate optimization, avoid floating-point arithmetic, etc.

    • Avoid improper use of walelock.

    • Use Job Scheduler.

Four, apk thin body

The app installation package size has no effect on app usage, but the larger the app's installation package, the higher the user download threshold, especially in the case of mobile networks, when users download the app, the size of the installation package is higher, so reducing the size of the installation package will allow more users to download and experience the product.

The composition of the Common Application installation package:

We can see:

    • Assets folder. Storing some configuration files, resource files, assets does not automatically generate the corresponding ID, but is obtained through the interface of the Assetmanager class.

    • Res. RES is an abbreviation for resource, which holds the resource file and automatically generates the corresponding ID and maps to it. R file, Access uses the resource ID directly.

    • Meta-inf. Save your app's signature information to verify the integrity of the APK file.

    • Androidmanifest.xml. This file is used to describe the configuration information of the Android app, the registration information of some components, the permissions to use, and so on.

    • Classes.dex. Dalvik bytecode program, let Dalvik virtual machine executable, in general, Android application in the Android SDK when packaging through the DX tool to convert Java bytecode to Dalvik byte code.

    • RESOURCES.ARSC. A mapping relationship between resource files and resource IDs is recorded to find resources based on resource IDs.

Common scenarios for reducing the size of installation packages

    • Code obfuscation. Use the Proguard Code obfuscation tool, which includes features such as compression, optimization, and obfuscation.

    • Resource optimization. For example, use Android Lint to remove redundant resources, minimize resource files, and so on.

    • Picture optimization. For example, use the AAPT tool to compress images in PNG format, and reduce the number of image color bits.

    • Avoid duplicate functions of the library, use WEBP picture format, etc.

    • Plug-in. For example, the function module on the server, on-demand download, you can reduce the size of the installation package.

V. Summary:

Last but not least, performance optimization is a very challenging task, with a lot of methods for analyzing memory and optimizing memory, but the real optimization work is much more than simple, here are just a few ways to get started, and the perfect memory optimization, memory analysis is not a day of work, Requires the developer's deep technical skills to be patient.

Android App Performance Optimization (latest summary)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.