Avoid memory leaks on Android

Source: Internet
Author: User

Android applications is, at least on the T-mobile G1, limited to MB of heap. It ' s both a lot of memory for a phone and yet very little for what some developers want to achieve. Even if you don't plan on using the all of the this memory, you should use as little as possible to let other applications run WI Thout getting them killed. The more applications Android can keep in memory, the faster it'll be is for the user to switch between his apps. As part of my job, I-ran into memory leaks issues in Android applications and they is most of the time due to the same MI Stake:keeping a long-lived reference to a Context.

on Android, a  Context  is used for many operations but mostly to load and access resources. The widgets receive a  Context  parameter in their constructor. In a regular Android application, you usually has a kinds of  Context , activity and  Application. It's usually the first one, the developer passes to classes, and methods that need a  Context :

@Override protected void onCreate (Bundle state) {  super. OnCreate (state);     New TextView (this);  Label.settext ("Leaks is bad");    Setcontentview (label);}

This means, which has a reference to the entire activity and therefore to anything your activity is holding onto; Usually the entire View hierarchy and all its resources. Therefore, if you leak the Context ("leak" meaning your keep a reference to it thus preventing the GC from collecting it), yo U leak a lot of memory. Leaking an entire activity can is really easy if you ' re not careful.

When the screen orientation changes the system would, by default, destroy the current activity and create a new one while P reserving its state. In doing so, Android would reload the application ' s UI from the resources. Now imagine your wrote an application with a large bitmap so you don ' t want to load on every rotation. The easiest-keep it around and not have to reload it on every rotation are to keep in a static field:

Private Static drawable sbackground; @Override protected void onCreate (Bundle state) {  super. OnCreate (state);     New TextView (this);  Label.settext ("Leaks is bad");     if NULL ) {    = getdrawable (r.drawable.large_bitmap);  }  Label.setbackgrounddrawable (sbackground);    Setcontentview (label);}

This code was very fast and also very wrong; it leaks the first activity created upon the first screen orientation Chang E. When a drawable is attached to a view, the view is set as A callback on the drawable. In the code snippet above, this means the drawable have a reference to the  TextView  which itself have A reference to the activity (the  Context ) which in turns have references to pretty much anything (depend ing on your code.)

This example are one of the simplest cases of leaking the  Context  and You can see how we worked a Round it in thehome screens ' s source code  (look for the  unbinddrawables ()  method) by setting T He stored drawables ' callbacks to NULL if the activity is destroyed. Interestingly enough, there is cases where you can create a chain of leaked contexts. I can ' t remember an exact case right now, but I had a fixed a couple of those, and they is bad. They make your run out of memory rather quickly.

There is the easy ways to avoid context-related memory leaks. The most obvious one are to avoid escaping, the context outside of its own scope. The example above showed the case of a static reference but inner classes and their implicit reference to the outer class can be equally dangerous. The second solution is to use the Application context. This context would live as long as your application is alive and does not depend on the activities life cycle. If you plan to keeping long-lived objects that need a context, remember the Application object. You can obtain it easily by calling Context.getapplicationcontext () or activity.getapplication ().

In summary, to avoid context-related memory leaks, remember the following:

    • Keep long-lived references to a context-activity (a reference to an activity should has the same life cycle as the Activity itself)
    • Try using the context-application instead of a context-activity
    • Avoid non-static Inner Classes in an activity if you don't control their life cycle, use a static inner class and make a W Eak reference to the activity inside

And remember that a garbage collector are not a insurance against memory leaks. Last but not least, we try to make such leaks harder to make happen whenever we can.

Original address: http://www.curious-creature.com/2008/12/18/avoid-memory-leaks-on-android/comment-page-1/

Avoid memory leaks on Android

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.