"Translate" Android to avoid memory leaks (context and context.getapplicationcontext of activity)

Source: Internet
Author: User
Tags home screen

Excuse address: http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html, English text after translation

Android app at least, in T-mobile G1 this model, there is 16MB of heap memory. This capacity is great for mobile phones, but it's a bit less for some developers. For all other applications to run without being killed by the system, even if you do not plan to use all of the allocated capacity, you should try to use these capacities sparingly.

The more apps Android can save, the quicker the user can switch apps. I ran into a memory leak at work, and they occur for many reasons because of the same error: The save context holds a long lifetime reference

In Android development, the context is needed in many operations, most of which are used to load and manipulate application resources. This is why some components receive a context parameter in their constructors. Typically there are two species of context:activity and application in an Android application. It is common for everyone to pass the first context (Activity) to the methods and classes that require this parameter: the code is as follows

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

This means that these views hold a reference to the entire activity, and therefore also to the object held by the activity. These objects are usually the hierachy of the entire view and the resources they use. So, once your context has a memory leak (leak: It means you are referencing the context, causing it to not be recycled by GC ), it means that you will leak a lot of memory. If you are not careful, the memory leak of activity is very easy to appear.

When the orientation of the screen (orientation) changes, the system defaults to destroying the current activity and then saving the state, creating a new activity. When you do this, Android reloads the UI from the resources. When you do this, Android will re-load the UI from resources. Imagine that you are writing an application that has a large picture (bitmap) that you do not want to load during any rotation operation. So if you want to save it in any rotation, the simplest way to do it without reloading is to declare it as a ' static member variable ' (static field): The code is as follows

Private Staticdrawable sbackground; @Overrideprotected voidonCreate (Bundle state) {Super. OnCreate (state); TextView label=NewTextView ( This); Label.settext ("Leaks is bad"); if(Sbackground = =NULL) {Sbackground=getdrawable (R.DRAWABLE.LARGE_BITMAP);  } label.setbackgrounddrawable (Sbackground); The case of this code is that TextView holds a reference to the context of an activity, and then because it holds a reference to a static variable drawable, the TextView is the same as the life cycle of the class. Thus the context of the activity is also held for a long time, causing the activity to be referenced by a person and not be recycled by GC Setcontentview (label);}

This code will run quickly, but it's also wrong. It will reveal the first activity that was created when the screen was rotated. When a Drawable object is assigned to a view, the view is set to the drawable callback (callback). In the above code slice, this means that the Drawable object holds a TextView reference, and TextView holds a reference to the activity for the reason of the context, and therefore holds many other references, depending on your code.

This code is one of the simplest examples of a context-led memory leak.

Android applications is, at least in 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< /span>.

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 two kinds of  Context ,  activity  andapplication . 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), Y Ou 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 whil e preserving 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 has to reload it on every rotation was to keep in a static field:

 private  static   drawable Sbackground; @Override  protected  void   OnCreate (Bundle state) { super  .oncreate (state); TextView label  = new  TextView (this   );    Label.settext ( Leaks is bad ");  if  (sbackground = = null   = getdrawable (R.DRAWABLE.LARGE_BITMAP);    } label.setbackgrounddrawable (Sbackground); Setcontentview (label);}  

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

This example was one of the simplest cases of leaking the and you can see how Context we worked around it in the Home screen ' s source code (look in the unbindDrawables() method) by setting the stored drawables ' callbacks to NULL when the activity is Destroye D. Interestingly enough, there is cases where you can create a chain of leaked contexts, 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 Callingcontext.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. The solution to this issue are to use a static inner class with a weakreferenceto the outer class, as do in Viewroot and Its W inner class for instance
    • A garbage collector is A insurance against memory leaks

"Translate" Android to avoid memory leaks (context and context.getapplicationcontext of activity)

Related Article

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.