Avoid long-term holding of a context reference causing a memory leak

Source: Internet
Author: User
Tags home screen

On Android, context can be used for many operations, but most of the time it is used to load and use resources. This is why all widgets accept a context parameter in their constructor. In a typical Android app, you usually have two kinds of context: activity and application, respectively. Often, when our classes and methods need to be used in the context, we pass on the context of activity.

[Java]
  1. @Override
  2. protected void onCreate (Bundle state) {
  3. Super. OnCreate (state);
  4. TextView label = new TextView (this);
  5. Label.settext ("Leaksis bad");
  6. Setcontentview (label);
  7. }

This means that views have a reference to the entire activity, which refers to everything that your activity has, and typically, this refers to the full view hierarchy and all its resources. So if you leak a context ("leak" means that you keep a reference to it so that it can't be recycled by the garbage collection mechanism), it means you're leaking a lot of memory. If you're not careful, it's really easy to leak all the resources of an activity. when the orientation of the screen changes, the system defaults to destroying the current activity and creating a new activity while maintaining its original state. When you do this, Android reloads the app's UI from the resource. Now, imagine that you wrote an app that has a big bitmap. You don't want to reload it every time you spin. The simplest way to make a bitmap persist without reloading in every direction is to put it in a static domain:

[Java]
  1. Private Static Drawable Sbackground;
  2. @Override
  3. protected void onCreate (Bundle state) {
  4. Super. OnCreate (state);
  5. TextView label = new TextView (this);
  6. Label.settext ("Leaksis bad");
  7. if (Sbackground = = null) {
  8. Sbackground = getdrawable (R.drawable.large_bitmap);
  9. }
  10. Label.setbackgrounddrawable (Sbackground);
  11. Setcontentview (label);
  12. }
The code is fast, but the error is serious: it leaks the first activity, the activity that was created when the first screen changed. When a drawable is associated with a view, the view is equivalent to a callback set on the drawable. In the code snippet above, this means that drawable has a textview reference, and the TextView has an activity reference (Context), which in turn refers to almost everything (depending on your code).

This example shows one of the simplest context leaks, and you can see how we solve the problem in the source code of Home screen (find the Unbinddrawables () method), which is when the activity is destroyed Drawables The callback is set to null. Interestingly, you can create a series of context leaks in a number of situations, which is very bad. They'll be you soon memory overflows.
There are two simple ways to avoid context-related memory leaks. The most notable one is to avoid the context escaping from his own range. The example above shows the use of static references, while the inner classes and their implicit references to external classes are equally dangerous. The second method is to use the application context. The life cycle of this context is as long as your application's life cycle, not the activity's life cycle. If you want to keep a long-lived object, and this object needs a context, remember to use the Application object. You can get it by calling Context.getapplicationcontext () or activity.getapplication ().
To summarize, to avoid context-related memory leaks, keep the following in mind:
1. Do not use the context of the activity for long-term references (the lifetime of an activity reference should be the same as the life cycle of the activity)
2, try to use the context of the application to replace and activity-related context
3, if the life cycle of a acitivity non-static inner class is not controlled, then avoid using it; use a static inner class and use a weak reference to the activity in it. The solution to this problem is to use a static inner class, and have a weakreference to its outer class, just as in the case of inner class W in Viewroot.
4. The garbage collector cannot handle memory leaksleakagethe protection

Avoid a long-held reference to a context that causes a memory leak

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.