Android Client performance optimization (Meizu Senior engineer without reservation)

Source: Internet
Author: User

This article by the Meizu Technology Limited Company senior Android development Engineer Degao (embedded Penguin Circle Original team member) writes, is Degao in the embedded Penguin Circle published the first original article, unreservedly summarizes to share its in leading Meizu multiple project development The Android client performance optimization experience , very practical value!

As we all know, a good product, in addition to powerful, good performance is also essential. Surveys show that nearly 90% of respondents will be uninstalled because of poor app performance, which is the number one cause of frustration for app users.

What are the performance metrics for Android clients? How do I find and locate client performance issues? Combining with the development practice of several projects, this paper gives the important index items to be concerned, as well as the general steps to locate and solve the performance problems.

Performance optimization should be done throughout the entire cycle of functional development, rather than having to do it one after the other. It is best to check performance against the standard before each release.

Remember: Product = performance x Function!

First, the performance check

1. Start speed

1) The starting speed here refers to the speed of cold start, that is, the speed of the restart after the application, this is mainly compared with your competitor.

2) You should not take any time-consuming action in the application and activity lifecycle callbacks, which is probably the best you can do in a callback such as Oncreate,onresume,onstart, not more than 400ms, Otherwise the user will feel a noticeable lag after clicking on your app icon on the desktop.

2. Interface switch

1) When the operation is applied, the interface and animation should not lag obviously;

2) You can debug GPU over-drawing by opening settings---developer options on your phone, and then manipulate the app to see if the GPU is over-line for preliminary judgment;

3. Memory leaks

1) Back exit should not have a memory leak, a simple check is to exit the application, with the command ' adb shell dumpsys meminfo Application package name ' to see if ' activities views ' is zero;

2) The memory ' total ' after multiple entry and exit should not change too much;

4. Ontrimmemory Callback

1) The application responds to this callback to release the non-required memory;

2) Verify that the memory size can be viewed by command ' adb shell dumpsys gfxinfo application Package name-cmd Trim 5 ', and then by command ' adb shell dumpsys meminfo application package name '.

5. Over-rendering

Turn on the GPU over-draw switch in the settings, the interface over-draw should not exceed 2.5x; it is also open this debug switch, the interface overall display light, particularly complex interface, red area should not exceed the full screen of One-fourth;

6. Lint Inspection

1) static scanning of engineering code via analyze->inspect code in Android Studio, identification of potential problem code and modification;

2) 0 Error & 0 warning, if it does not resolve, you need to give reasons.

7. Reflection Optimization

1) Reduce the reflection call in the code;

2) cache The return value of the frequent call;

8. Stability

1) for 48 consecutive hours monkey should not appear flash back, ANR problem.

2) If the application access to the data buried in the SDK, such as Baidu Statistical SDK, these SDK will be the application of the crash information back, developers should pay attention to these statistics to the crash log every day, strictly control the crash rate of the application;

9. Power consumption

1) After the application into the background should not be abnormal consumption of power;

2) After the application, quit the app, let the app in the background, after some time through the ' adb shell Dumpsys batterystats ' view the power consumption log to see if there is an exception.

Ii. common causes of performance problems

Performance issues generally boil down to three classes:

1. UI lag and Stability: this kind of problem users can directly perceive, the most important;

2. Memory issues: Memory problems are mainly manifested by memory leaks, or memory jitter caused by improper memory usage. If there is a memory leak, the application will continue to consume memory, causing frequent GC to cause the system to stutter, or oom error, and memory jitter will also cause UI Kaka.

3. Power consumption problem: will affect the battery life, performance is unnecessary self-start, improper holding the lock causes the system to sleep normally, system sleep wake up the system frequently;

Iii. common causes and analysis methods of UI Scorecard

The following sections describe the common causes of these problems and general steps to analyze them.

1. Common causes of Lag

1) Make the UI thread incurring by making a slight time-consuming operation in the UI threads;

2) layout layouts are too complex to render within 16ms;

3) An excessive number of animations are performed at the same time, resulting in excessive CPU or GPU load;

4) View over-drawing, which causes some pixels to be drawn multiple times within the same frame time, which can overload the CPU or GPU;

5) View frequent trigger measure, layout, resulting in measure, layout accumulated time-consuming and the whole view of the frequent re-rendering;

6) memory frequently triggers too many GC (memory is frequently created in the same frame), causing temporary blocking of rendering operations;

7) Redundant resources and logic lead to slow loading and execution;

8) Worker thread priority is not set to

Process.thread_priority_background

Causes the background thread to preempt the UI thread CPU time slices, blocking rendering operations;

9) ANR;

2. General steps of the lag analysis

1) solve over-drawing problems

> Debugging GPU over drawing in Settings--developer options--to see if the corresponding interface is over-drawn, if one is resolved first:

> Positioning Transition Plot Area

> Location Confirmation and modification using the tools provided by Android (Hierarchyview, Tracer for OpenGL ES)

> Navigate to a specific view (XML file or view)

> Analyzing the reason for transition drawing through code and XML files

> optimization based on specific conditions

> further optimization using the lint tool

2) Check if there is a time-consuming operation for the main thread:

Strict mode (Strictmode) is a runtime detection mechanism provided by Android to detect some of the irregular operations of the code at runtime, the most common scenario being the IO operation for discovering the main thread. The application can use Strictmode to find some coding omissions as much as possible.

> Open Strictmode

>> for Applications, Android offers a best practice: as early as possible in

The life cycle Enable Strictmode,oncreate () method of the Android.app.Application or android.app.Activity is the best time to detect violations on more code execution paths as soon as they are opened.

>> Monitoring Code

public void OnCreate () {if (Developer_mode) {strictmode.setthreadpolicy (New StrictMode.ThreadPolicy.Builder ().     Detectall (). Penaltylog (). build ()); Strictmode.setvmpolicy (New StrictMode.VmPolicy.Builder (). Detectall (). Penaltylog (). build ()); } super.oncreate ();}

If the main thread has operations such as network or disk read and write, there will be a log output of "D/strictmode" tag in logcat, thus locating the code for the time-consuming operation.

3) If the main thread has no time-consuming operation and there is still a lag, there are some logic problems that must be manipulated in the UI thread, such as control measure, too much time-consuming layout, and so on, which can be analyzed by TraceView and systrace.

4) Traceview:traceview is mainly used as hot spot analysis to find out the most need to optimize the point.

> Open Ddms and select a process, then click on the "Start method Profiling" button above (the red dot turns black to start running), then manipulate our stuttering UI, then click "Stop Method Profiling", The following interface will open:

The figure shows the method invocation relationships, the number of calls, and the time-consuming proportions during trace. Through analysis, we can find out the suspicious time-consuming function and optimize it.

5) Systrace: Crawl trace:

> Execute the following command:

$ cd android-sdk/platform-tools/systrace$ python systrace.py--time=10-o mynewtrace.html sched gfx View WM

> operates the app and then generates a mynewtrace.html file that opens with chrome.

The > diagram is as follows:

By analyzing the graph above, we can find out the time-out problem of the Layout,measure,draw obviously.

6) Import the following plug-ins, you can use the method to add @debuglog to print the method time-consuming:

Build.gradle:buildscript {dependencies {

Print plug-in for easy debugging of performance issues. By adding @debuglog to the method, you can output the invocation parameters and the execution time.

Classpath ' com.jakewharton.hugo:hugo-plugin:1.2.1 '}}

Print plug-in for easy debugging of performance issues. By adding @debuglog to the method, you can output the invocation parameters and the execution time.

Apply plugin: ' Com.jakewharton.hugo ' java: @DebugLogpublic void Test (int a) {int b=a*a;}

Iv. Memory performance Analysis and optimization

1. Memory leaks

This problem is generally used in the project Leakcanary basic can be done, configuration is quite simple:

build.gradle:dependencies {debugcompile ' com.squareup.leakcanary:leakcanary-android:1.3.1 '//or 1.4-beta1 Releaseco Mpile ' com.squareup.leakcanary:leakcanary-android-no-op:1.3.1 '//or 1.4-beta1 testcompile ' com.squareup.leakcanary: leakcanary-android-no-op:1.3.1 '//or 1.4-BETA1}
Java:public class Exampleapplication extends application {@Override public void onCreate () {super.oncreate ();  Leakcanary.install (this); }}

Once a memory leak occurs, a notification is generated in the notification bar, which opens to see the leaked objects and the reference path:

2. Memory Jitter

If the code has the behavior of allocating objects in code that executes multiple times, such as OnDraw or for loops, it can result in more GC times during the run and affect UI smoothness. In general, these problems can be detected through the lint tool.

Five, power consumption optimization recommendations

Power optimization is mainly to pay attention to try not to affect the phone into hibernation, that is, the correct application and release of Wakelock, the other is not frequent wake-up phone, the main is the correct use of alarm.

Six, some good code practice

1. Use the service in moderation

2. Free memory when the interface is not visible

3. Free memory when memory is tight

4. Avoid wasting memory on bitmap

For large pictures, first get the size of the picture information, according to the actual need to show the size calculation insamplesize, the last decode;

Public static bitmap decodesampledbitmapfromfile (string filename,int reqwidth,  Int reqheight)  {// first decode with injustdecodebounds=true to check  dimensionsfinal bitmapfactory.options options = new bitmapfactory.options (); O ptions.injustdecodebounds = true; Bitmapfactory.decodefile (filename, options);// calculate insamplesizeoptions.insamplesize  =reqheight); Calculateinsamplesize (options,reqwidth,// decode bitmap with insamplesize  setoptions.injustdecodebounds = false;return bitmapfactory.decodefile (filename,  options);} Public static int calculateinsamplesize (Bitmapfactory.options options,int reqwidth,  int reqheight)  {// raw height and width of imagefinal int  height = options.outheight;final int width = options.outwidth;int insamplesize = 1;if  (height > reqheight | |  width > reqwidth)  {if  (width > height)  {insamplesize =  math.round (float)  height /  (float)  reqheight);}  else {insamplesize = math.round (float)  width /  (float)  reqwidth);}} Return insamplesize;}

5. Using the optimized data collection

6. Use abstract programming with caution

7. Avoid using the dependency injection framework as much as possible

Many of the dependency injection frameworks are based on the principle of reflection, although it can make the code look concise, but it is detrimental to performance.

8. Use external libraries carefully

9. Optimize Overall performance

10. Use Proguard to remove unwanted code

Android {buildtypes {release {minifyenabled true shrinkresources true Progua Rdfiles getdefaultproguardfile (' proguard-android.txt '), ' Src/main/proguard-project.txt ' SigningConfig signingCo Nfigs.debug}}

11. Careful use of exceptions, abnormal performance unfavorable

Throwing an exception begins with creating a new object. The constructor for the Throwable interface is named

Fillinstacktrace () Local method, Fillinstacktrace () method check stack, collect call trace letter

Interest. As long as an exception is thrown, the VM needs to adjust the call stack, because during the process it creates a

A new object.

Exceptions can only be used for error handling and should not be used for control procedures.

The following examples are not good:

try {startactivity (Intenta);} catch () {startactivity (INTENTB);}

The following statement should be used to determine:

if (Getpackagemanager (). Resolveactivity (Intenta, 0)! = NULL)

Do not use the Try/catch statement in the loop, you should put it on the outermost layer, use system.arraycopy () instead of for the For loop copy.

More Android, Linux, embedded and IoT original technology sharing please follow the public number: embedded Penguin ring.

Android Client performance optimization (Meizu Senior engineer without reservation)

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.