Android Studio analyzes memory leaks

Source: Internet
Author: User

Before using eclipse, we used DDMS and mat, not only the use of complex steps, but also to manually troubleshoot the location of memory leaks, operation is more troublesome. Later with the trend of Android studio, I also abandoned eclipse to join as.

Android Studio also started to support automatic memory leak checking, and it was easier to operate.

As we all know, it is impossible for the system to allocate all the memory to our application. Each program will have a memory limit that can be used, which is called the heap size. Different mobile phones, heap size is not the same, with the current hardware equipment is increasing, the heap size has also increased. If you want to know what the heap size of your phone is, you can call the following code:

Activitymanager manager = (activitymanager) Getsystemservice (context.activity_service);   int heapsize = Manager.getmemoryclass ();  

The result is returned in megabytes, where the memory used to develop the application does not exceed this limit, or outofmemoryerror will occur. Therefore, for example, in our program we need to cache some data, we can determine the capacity of the cache data according to the heap size.

The following describes the use of Android Studio Monitor to detect memory leaks, chestnuts as follows:

A thread is called every time the mainactivity is started, and then the thread executes the runnable run method because runnable is an anonymous internal object and therefore has a mainactivity reference, so
Start Mainactivity 4 times, and finally exit. In common sense, mainactivity will be destroyed and recycled, but that may not be the case.

Open Android Studio, compile the code, run the app on the emulator or the real machine, click on Monitor tab under Android Monitor and go to the following screen

In the memory column, you can observe the dynamic use of different times of the app, click to manually trigger GC, click to enter the Hprof Viewer interface, view the Java heap, switch to the package Tree view, easy to view, click on the Analyzer Task,android Monitor can automatically analyze leaked activity for us, 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.

See, on the left is an object in memory, there are still 4 mainactivity instances on the right, we are clearly all exited, how still exist, this indicates that there is a memory leak.

We look at reference Tree and see this$0CitedUseThe this ac ti vi ty th is$ 0 indicates the meaning of the inner class, which is an inner class that references mainactivity and this$0 is referenced by target, Target is a thread. The reason for the memory leak is that mainactivity is referenced by the inner class, and the inner class is used by the thread, so it cannot be freed to cause a memory leak.  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.

Android Studio analyzes memory leaks

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.