"Go" ... Android application memory leak analysis, improvement experience Summary

Source: Internet
Author: User

Original website: Http://wetest.qq.com/lab/view/107.html?from=ads_test2_qqtips&sessionUserType=BFT. Params.194206.taskid&aduin=554147273&adsession=1467939955&adtag=client. qq.5479_.0&adpubno=26582

Objective

With the memory leak detection and improvement of several applications over the past few days, the results are obvious:

    • When completely exiting the application, manually triggering GC, from the original occupied memory 100 m to less than 20M;

    • After manually triggering the GC, the amount of activity and view is approaching 0 through the adb shell Dumpsys meminfo packagename-d (no zeroing is due to a memory leak in the SDK, which requires an intermediate layer to process);

    • Found a memory leak in the SDK (the memory leak and solution caused by Android Inputmethodmanager);

    • Found a MTK webview memory leak (Org.chromium.android_webview. Awpasswordhandler.java private static Awpasswordhandler sinstance = null causes a memory leak).

From the results, I analyze and improve the memory leak method is right, the process is not complex, so can be summarized as a share.

Principle

For performance issues, analysis and improvement are necessary to follow these guidelines:

    • All look at the data to speak, can not follow the feeling go, feel which have problems to change, it is likely to backfire;

    • Performance optimization is a continuous process, need to constantly improve, do not think about one go;

    • For performance problems, it is not necessarily necessary to improve, limited by the architecture or other reasons some problems may be difficult to improve, must first ensure that the use, before considering the good.

    • It is important to verify that any changes in one place need to be verified to avoid other problems due to improved performance.

Steps

Here are my steps to address this performance issue with memory leaks:

Prioritize common memory leak issues

To solve the common memory leak problem, this process can use the Analyze-inspect code of Android Studio to do static analysis, common memory leak problems are:

  • A memory leak caused by a non-static inner class, such as handler, is solved by writing an inner class as a static inner class, using a soft reference/weak reference in a static inner class to hold an instance of the outer class, eg:

    StaticClassExercisehandlerExtendshandler{Privatesoftreference<Exerciseactivity> exerciseactivitysoftreference =null; public exercisehandler ( Exerciseactivity exerciseactivity) {exerciseactivitysoftreference = new softreference<exerciseactivity> (exerciseactivity);}  @Override public void Handlemessage (message msg) { Exerciseactivity exerciseactivity = Exerciseactivitysoftreference.get (); if (null! = exerciseactivity) { Super.handlemessage (msg); Switch (msg.what) {case msg_xx:exerciseactivity.***; break; default: break;}} } 
  • After IO operation, there is no memory leak caused by closing the file, such as cursor, FileInputStream, FileOutputStream is not closed after use, this problem can be checked out by static code analysis in Android Studio 2.0. The direct improvement is possible;

  • After using Typedarray in Custom view, there is no recycle, this problem can be checked out by static code analysis in Android Studio 2.0, and can be improved directly;

  • Some places use the context of the four components, and still hold the memory leaks caused by their context after leaving these components, which is a common understanding and should be followed by rules in the process of writing code. Using the context of application can solve this kind of memory leakage problem, as to what circumstances should use the four components of the context, when should use the application context can see the following table:


    Application usage Scenarios

  Note : We notice that there are some numbers added to the number, in fact, these are the ability to say yes, but why is no? One explanation below:

1、数字1:启动Activity在这些类中是可以的,但是需要创建一个新的task,一般情况不推荐;2、数字2:在这些类中去layout inflate是合法的,但是会使用系统默认的主题样式,如果你自定义了某些样式可能不会被使用;3、数字3:在Receiver为null时允许,在4.2或以上的版本中,用于获取黏性广播的当前值。(可以无视);4、ContentProvider、BroadcastReceiver之所以在上述表格中,是因为在其内部方法中都有一个context用于使用。
    • There is also a memory leak, but in the analysis of memory leaks should be resolved: The same app, the picture in a different drawable folder, the same device occupies the memory situation is not the same, see: About the image size in Android, The research and analysis of the relationship between memory consumption and Drawable folder. To solve this problem, follow these guidelines:

      1, the UI only provides a set of high-resolution diagram, the picture is suggested in the drawable-xxhdpi folder (placed in the XXXHDPI or higher resolution folder is not necessary, weigh the pros and cons, to take care of mainstream equipment), so in low-resolution devices, the size of the picture is just compression, There is no case of memory increase;

      2, related to the desktop plug-in or do not need to zoom the picture, placed in the Drawable-nodpi folder, the folder under the picture on any device will not be scaled.

The tool checks for memory leaks after running the program

Through the above steps, most of the memory leaks in the application can be solved, there are some memory leaks, need to run the program, analyze the running memory snapshot to solve, such as no anti-registration after registration, static member variables in the class caused by memory leaks, memory leaks in the SDK, and so on. Solving this type of problem can be done in two steps:

    • There are two convenient ways to detect memory leaks by locating the memory leak detection Tool First:

      1, one is the use of open source project Leakcanary, need to add to the code, run to generate analysis results;

      2, another way is to use the ADB shell dumpsys meminfo packagename-d command, before entering an interface to see the number of activity and view, after exiting the interface to see the number of activity and view again, Compare the number of activity and view changes before and after entry, and if there is a discrepancy, there is a memory leak (remember to manually trigger the GC before using the command to view the number of activity and view).

      Note: in Android Studio, you can get the memory information for the currently selected process in the following ways:

    • Then through the mat to run a memory snapshot of the program to do a detailed analysis, for the use of mat, there are many high-quality articles on the Internet, such as: Android performance optimization using mat analysis of memory leaks, before using the mat, it is necessary to know these points:

      1. Do not expect Mat to explicitly tell you where there is a memory leak, which requires you to first locate the class that may have a memory leak based on the previous step, and then use the mat to confirm if there is a memory leak, where there is a memory leak;

      2, with the help of retained size analysis of a class and its related instances of memory consumption, if this class retained size is larger, priority analysis;

      3, check if there is a memory leak in a class, exclude its soft/weak/virtual reference, right-click a class →merge shortest Paths to GC roots→exclude all Phantom/weak/soft etc.references.

Verify Improvement Results

Based on personal experience, I generally verify the effect of the improvement, run the program, each function run over, make sure that there is no problem, completely quit the program, manually trigger GC, and then through the ADB shell Dumpsys meminfo packagename- d See whether the number of activivites and views is approaching 0, if not 0, through the Leakcanary check where there may be memory leaks, continue through the mat analysis, the cycle, improve to their satisfaction.

"Disclaimer: This article has been authorized to transfer from a simple book, Zhang Mingyun, without permission, no reprint." 】

This article original address: http://www.jianshu.com/p/33d3f89f7941

"Go" ... Android application memory leak analysis, improvement experience 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.