Android memory that thing.

Source: Internet
Author: User

Long time no write, not forget, also is not lazy, is because confused ~ ~ Don't know what to learn, what to write, what to walk the road, what to do like the person. I clumsy, do not know how to speak to others, I would like to share, so I write, whether it is right, wrong, I hope we can take its essence to its dross, do not mislead you because of me. No more nonsense to say ~ ~

Is your application memory leaking?

To see if there is a memory leak, first we need to see the memory information, how to see the memory information? Here is a way to open eclipse to connect the phone, to Ddms, select the app to analyze, click on the update heap is the icon in 1, click the 1 icon will appear in the application process to analyze the 2 icon, in 4 location can see the memory information of the app.


Memory information see, How do you know there is a memory leak? As you can see the amount of memory that the analysis application has requested, that is, the value of the 3 position, it is possible to determine if there is a memory leak based on the change in this value. How do you judge that? For example, we want to determine the first interface into the analysis application is not a memory leak, we can operate, first exit the application, and then click on the cause GC, and so on 3 position value stable, recorded, and then into the application, such as the first interface loading completed, then quit the application, then click Cause GC, The value of the 3 position is stable, then recorded, repeated operation several times, to see our recorded values, if the growth trend, the analysis of the application of the first interface has a memory leak problem, if the horizontal trend, indicating that there is no memory leak problem.

Where's the memory leak?

To know where the memory leaks, this requires the installation of a tool called Mat, how to install the Baidu Bar, here no longer nonsense. Similarly, go to open eclipse to connect the phone, go to Ddms, select the app to be analyzed, then click on the location of a, that is, dump HPROF file.


Wait a moment, the following window will pop up


Select Leak Suspects report and click Finish to go to the following window



Click on the "a" icon, the icon will appear in B, and then select GroupBy class loader in B, you can see the application for analysis of the requested object information, objects is the location of C, is the number of applications, shallow heap is the size of the object itself occupied memory , the retained heap is the sum of the shallow heap of the object itself and the objects directly or indirectly referenced to it, that is, the object can be recycled to the total memory after the GC. How do you determine where the memory leaks are through these numbers? And then the above example shows that we go to the first interface, which is the first activity, we know that when we exit the activity, we release the resources occupied by the activity, so the number of objects is not related to the number of times you start the activity. So we first record the number of objects, and then multiple in and out of the analysis application, and then generate Hprof files, and then see a objects number only increase does not decrease, indicating that the object has a memory leak. Of course a memory leak in a object may be caused by a reference to the B object to a, so we're going to find out if that object is not released causing a memory leak. The rest is up to you, one to check the number of things that have been growing.

Context How big is the threat to memory?

The context here is not application context, but the main activity. Before the online search memory overflow How to deal with, always say let the context released, so do, but still confused. Today we will talk about this context. We go on to the question above, when we monitor a lot of objects are growing, and the number of these objects is equal, as in C area many objects are 2, then we should pay attention to, is not a context is not released. A layout, Handler, thread, and so on, created in the activity, will save an activity object, and if one of these does not release the activity, it will cause all objects in that activity to be freed. If there is a large point in the activity bitmap not active release, the hidden trouble can not be described. I have met once before, is handler not released, resulting in the context is not released, and the context of the larger bitmap is not released, resulting in every time into the activity memory to the nearly 3M of the speed of growth, back and forth into a number of oom.

Bitmap How much memory is it?


First, determine how the bitmap image size is calculated. Let's calculate the bitmap size of a pixel 500x500 with a bit depth of 24. We all know that bitmap is characterized by a pixel that occupies a bit depth, such as a bit depth of 24, that is, a pixel occupies 24b (bit), that is 3B.

Size (B) = width (pixels) * Height (pixels) * bit depth/8.

Size (KB) = size (B)/1024.

So the image size we mentioned above is: 500*500*24/8/1024=732KB.

And what is the size of this bitmap on Android phones? We write a piece of code to test it, of course, the other object size can be so to test size.

<span style= "FONT-SIZE:18PX;" >    private void Testbitmapsize (context context) {        bitmapdrawable drawable = (bitmapdrawable) Context.getresources (). getdrawable (R.drawable.test_bitmap);        Bitmap Bitmap = Drawable.getbitmap ();        ANDROID.UTIL.LOG.D ("My_test", "Start----------");        System.GC ();        Bitmap.recycle ();        System.GC ();        ANDROID.UTIL.LOG.D ("My_test", "End----------");    } </span>

We crawl log as follows:

D/my_test (14667): Start----------

D/DALVIKVM (14667): Gc_explicit freed 9k,4% free 10122k/10503k, paused 1ms+4ms

D/DALVIKVM (14667): Gc_explicit freed976k, 13% free 9145k/10503k, paused 2ms+2ms

D/my_test (14667): End----------

According to this we can estimate that after the release of this bitmap, the memory freed up about 976KB size, will be nearly 1M of memory. If this is not released, it will soon overflow.

What can cause context not to be released?

I encountered the context is not released, is this, the application has a tumbling title, every time to go tumbling once, so I went to write:

It is easy to see from the code, each 5s,handler to send a message, and this handler in the activity is destroyed without release, so the inside view of the context is not released, and the context has more than 2M bitmap not active release , resulting in the application will be more than one context object, more than the space will be nearly 3M.

Bitmap do you need to release?

As stated above, the context does not release cause the inside of the bitmap is not released, if the context released the inside of the bitmap will be released? The answer is yes. I encountered above the memory leak, in the fact that the real reason is not found, I sent under the 2M of the bitmap did not voluntarily release, so in the end of the use of the initiative to release:

<p align= "left" ><span style= "font-size:18px;" ><strong><span style= "color: #7F0055;" >if</span></strong> (Bitmap! = <strong><span style= "color: #7F0055;" >null</span></strong> &&!bitmap.isrecycled ()) {</span></p><p align= "left" ><span style= "FONT-SIZE:18PX;" >    bitmap.recycle (); </span></p><p align= "left" ><span style= "font-size:18px;" >    bitmap = <strong><span style= "color: #7F0055;" >null</span></strong>;</span></p><p><span style= "FONT-SIZE:18PX;" >}</span></p>

After release every time into the application, really less than 2M, but there is almost 1M of space is not released, I am very puzzled, with the mat tool to see, found that the first activity generated by the context is not released, and then to find out, the handler message, Therefore, the active release of the handler message before the activity is destroyed:

<span style= "FONT-SIZE:18PX;" > Public    void Releaseres () {        mcontext = null;        if (Mhandler! = null && mhandler.hasmessages (handler_search_hot_word))            mhandler.removemessages (handler_ Search_hot_word);        Mhandler = null;    } </span>

As a result, I looked at the memory of the application and did not increase, basically kept near a fixed value. This is my whim, if my bitmap not to release, will not leak it, so I put the release bitmap the place commented out. I went to verify that the application was in and out of the application many times, and I found that the app remained basically near that fixed value. So I think that bitmap will be released with the release of the context. The question comes, why do you have to take the initiative to release bitmap? That is because before you quit the application, the space occupied by this bitmap is there, since no need, occupy space is wasted, in addition, if a place of bitmap is not released, and this place will be repeated call, that the consequences are unimaginable. So bitmap is no longer used when it is time to release, not necessarily, as long as you can ensure that memory enough.

Bitmap Where can the release be ignored?

The longest occurrence of this is the place where bitmap was modified:

<span style= "FONT-SIZE:18PX;"        > bitmapdrawable drawable = (bitmapdrawable) this.getresources (). getdrawable (R.drawable.test_bitmap);                Bitmap Bitmap = Drawable.getbitmap ();        ANDROID.UTIL.LOG.D ("Logtest", "bitmap.getwidth () =" +bitmap.getwidth ());                ANDROID.UTIL.LOG.D ("Logtest", "bitmap.getheight () =" +bitmap.getheight ());        Bitmap Newbitmap = Bitmap.createbitmap (Bitmap, 0, 0, 500, 500);                Bitmap newBitmap2 = Bitmap.createbitmap (Bitmap, 0, 0, 400, 400);        ANDROID.UTIL.LOG.D ("Logtest", "bitmap=" +bitmap);        ANDROID.UTIL.LOG.D ("Logtest", "bitmap.isrecycled () =" +bitmap.isrecycled ());        ANDROID.UTIL.LOG.D ("Logtest", "newbitmap=" +newbitmap);        ANDROID.UTIL.LOG.D ("Logtest", "newbitmap.isrecycled () =" +newbitmap.isrecycled ());        ANDROID.UTIL.LOG.D ("Logtest", "newbitmap2=" +NEWBITMAP2); ANDROID.UTIL.LOG.D ("Logtest", "newbitmap2.isrecycled () =" +newbitmap2.isrecycled ());</span>

This is how log is called:

D/logtest (27782): Bitmap.getwidth () =500

D/logtest (27782): Bitmap.getheight () =500

D/logtest (27782): [Email protected]

D/logtest (27782): bitmap.isrecycled () =false

D/logtest (27782): [Email protected]

D/logtest (27782): newbitmap.isrecycled () =false

D/logtest (27782): [Email protected]

D/logtest (27782): newbitmap2.isrecycled () =false


Obviously, when we do the image modification, if the transmission into the bitmap and output of the bitmap specifications of the same, then the return is the original, the same address, if the picture is different, then re-create a bitmap, and the original bitmap is not released. At this time is prone to problems, we will forget to release the original bitmap, if a number of images were re-modified, then the memory leak is serious, such as the ListView has pictures, and in the picture before we set the image processing, then if you forget to release the picture before the change, then the consequences will be disastrous.

<span style= "FONT-SIZE:18PX;" >    if (newbitmap! = null &&!newbitmap.isrecycled () && newbitmap! = bitmap) {newbitmap.recycle (); C2/>newbitmap = null;    } </span>
This simple few lines of code will save your memory.

Can I release the pictures in the layout to save memory?

There are methods on the Web to release unwanted images from the layout:

<span style= "FONT-SIZE:18PX;" >        //Set picture        bitmapdrawable drawable = (bitmapdrawable) this.getresources (). Getdrawable (R.drawable.test_ bitmap);        Mimageview.setbackgrounddrawable (drawable);                        Release picture        bitmapdrawable Drawablerel = (bitmapdrawable) mimageview.getbackground ();        if (Drawablerel! = null) {            System.GC ();            Size = Runtime.getruntime (). TotalMemory ();            Drawablerel.setcallback (null);            Drawablerel.getbitmap (). Recycle ();            Drawablerel = null;            System.GC ();            ANDROID.UTIL.LOG.D ("Test_my_log", "rel_size=" + (Runtime.getruntime (). TotalMemory ()-size));        } </span>

The log is like this:

D/test_my_log (29891): rel_size=0

D/test_my_log (29891): rel_size=0

D/test_my_log (30292): rel_size=0

D/test_my_log (30292): rel_size=0

D/test_my_log (30292): rel_size=0


The size of the freed memory is 0, which means that everyone will be self-employed.

today is the first to pull these, and then have the opportunity to continue to pull, or that sentence, to the great God for fun, to the later, to give a start, right and wrong everyone from a judgment, just don't make fun of my good ~



Android memory that thing.

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.