Memory leak detection and resolution based on Android studio all tips

Source: Internet
Author: User

Since Google released Android studio in 2013, Android studio has been replacing eclipse with its own good memory optimizations, cool UI themes, powerful auto-completion hints, and Gradle compiler support. Become the mainstream Android development IDE. Android Studio provides us with a good coding experience, as well as many tools for app performance analysis, making it easier for developers to analyze app performance. Google has been telling developers in the IO conference not to use cell phone memory sparingly, and beware of bad development practices that can lead to memory leaks in the app. Although the online detection of the app memory leaks article voluminous, but to use DDMS and mat, not only the use of complicated steps, but also to manually troubleshoot the location of memory leaks, operation is more inconvenient. In fact, Android Studio has started to support the automatic memory leak check, this article with everyone to explore the mystery of it.


What is a memory leak
The root search algorithm is used for garbage collection of Android virtual machines. The GC will traverse the heap starting from the root node (GC Roots). In the end, some of the garbage that is not directly or indirectly referenced to GC roots is reclaimed by GC. The reason for the memory leak is that there is an invalid reference, causing the object that would otherwise need to be GC not to be recycled.


Give me a chestnut.

    Private StaticLeak Mleak;@Override      protected   void  onCreate(Bundle savedinstancestate)  {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_second); Mleak =NewLeak (); }  class   Leak  {    }

Mleak is a static variable stored in a static zone, while leak is an inner class that holds a reference to the external class activity. This causes the activity to be destroyed, because it is held by the Mleak, so the system does not GC it, resulting in a memory leak.


And one of the most frequently made chestnuts.

 Public   class   Singleton  {Private StaticSingleton instance;PrivateContext Mcontext;  Private  Singleton(context context) { This. Mcontext = Context; }public static    Singleton  getinstance(context context)    {if(Instance = =NULL){synchronized(Singleton.class) {if(Instance = =NULL) {instance =NewSingleton (context); }            }        }returnInstance }}

If we pass in the activity when we call Singleton's getinstance () method. The activity will persist when the instance is not released. Thus causing a memory leak.
The workaround is to change the new Singleton (context) to New Singleton (Context.getapplicationcontext ()) so that it doesn't matter with the incoming activity.


Detection of memory leaks
Open Android Studio, compile the code, run the app on the emulator or the real machine, then click on the Monitor tab under Android Monitor to enter the following screen


in the memory column, you can observe the dynamic use of different times of the app, click can manually trigger GC, click to enter the Hprof viewer interface, view Java heap, such as

The Reference tree represents a reference to the instance from which you can see the cause of the memory leak, shallow size refers to the amount of memory that the object itself occupies, and retained size represents the sum of memory that the garbage collector can reclaim after the object is freed.
Here we take the palm of the city client as an example, to explore the method of memory leak detection.
Open Android Studio, compile the code, run the palm of the city, and start playing with our app, then watch the app's memory usage curve from within memory monitor and suddenly find that Nani!!! How memory usage is getting bigger, this is probably a memory leak, then click on the Manual GC, then click to watch Javaheap, click on the Analyzer task,android Monitor can automatically analyze the leaked activity for us, Analyze it as shown

in the reference tree, we can directly see the singleton object that holds the activity, navigate directly to the code in that single example, and discover that the code appears

public static     videotaghelper  getinstance(Context  Context)  {if(Taghelper = =NULL) {Taghelper =NewVideotaghelper (); } Taghelper.context = context;returnTaghelper; }

It's just the same mistake that was raised in the Chestnut, who wrote the code and dragged it out ...
We fixed the problem of checking out the memory leaks and ran the pre-and post-repair code on the same emulator and performed the same operation to see how they used the memory, as shown in


memory leak, memory consumption is about 43M

Fixed a memory leak with 36M of memory

Memory usage drops after fixing a memory leak problem 16.3%!!!

the causes of memory leaks are broadly divided into the following types of Android:

memory leaks due to 1.static variables
Because the life cycle of a static variable is ended when the class unload begins when the class loads, that is, the static variable is released when the program process dies, and if the activity is referenced in the static variable, the activity is referenced, Will not be released as the lifetime of the static variable, causing a memory leak.

Workaround:
When the activity is referenced by a static variable, use Getapplicationcontext because the application life cycle is the same as the static variable from the beginning of the program to the end.

2. Memory leaks caused by threads
Similar to the case in the example above, thread execution takes a long time and activity jumps out of the box because the thread or runnable is the acticvity inner class, so there is an instance of activity (because creating an inner class must depend on an external class), As a result, activity cannot be released.
Asynctask thread pool, more serious problem

Workaround:
1. Arrange the thread execution time reasonably, and the control thread ends before the activity ends.
2. Change the inner class to a static inner class and use weak reference weakreference to save the activity instance because the weak reference recycles it as soon as the GC finds it, so it can be recycled as quickly as possible.

3.BitMap consumes too much memory
Bitmap Resolution requires memory, but memory only provides 8M of space to bitmap, if the picture is too much, and does not recycle bitmap in time, it will cause memory overflow.

Workaround:
Load pictures after recycle compressed pictures in time

4. Memory leaks due to resource not being shut down in time
For example, some cursor not in time close will save the activity reference, causing a memory leak

Workaround:
Close in time in the Ondestory method

memory leaks due to the use of 5.Handler
Because of the use of handler, Handler sends a message object into MessageQueue and then looper polls the MessageQueue and then takes out the message execution, but if a message is not removed for a long time to execute, So because there is a Handler reference in the message, and Handler is generally an inner class object, the message references Handler, and Handler references the activity so that the activity cannot be recycled.

Workaround:
Static inner class + weak reference is still used to resolve

6. single-Case with parameters

If we pass in the activity when we call Singleton's getinstance () method. The activity will persist when the instance is not released. Thus causing a memory leak.
Workaround:

You can change the new Singleton (context) to New Singleton (Context.getapplicationcontext ()) so that it doesn't matter with the incoming activity.


Mastering the use of Android Monitor, mom no longer worry about my app will appear memory leaks!!!

Memory leak detection and resolution based on Android studio all tips

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.