Avoid Android Memory leakage

Source: Internet
Author: User
Tags home screen

Android applications are limited to a maximum of 16 MB of memory, at least on T-Mobile G1 (of course there are hundreds of megabytes of memory available now ). It includes two parts that the phone itself occupies and can be used by developers. Even if you do not intend to use all the memory, you should use as little memory as possible to avoid other applications to close your applications during running. The more applications that Android can maintain in the memory, the faster the user switches the application. As a part of my work, I carefully studied the memory leakage problem of Android applications. In most cases, they are caused by the same error, that is, a Context) long reference is maintained.

In Android, Context is used for many operations, but most of them load and access resources. This means that all widgets will accept a Context parameter in their constructor. In a qualified Android Application, you can use two contexts: Activity and Application ). An Activity is usually passed to a class or method that requires Context parameters:

Source code
 
 
  1. @Override
  2. protected void onCreate(Bundle state) {
  3. super.onCreate(state);
  4. TextView label = new TextView(this);
  5. label.setText("Leaks are bad");
  6. setContentView(label);
  7. }

This means that the View has a reference to the entire Activity and the reference is maintained for all objects in the Activity; usually they include the entire View level and all its resources. Therefore, if you "leak" Context (here, "leak" means that you keep a reference and organize GC to collect it), you will cause a large amount of memory leakage. If you are not careful enough, "leaking" an entire Activity is very simple.

When the screen direction changes, the system will destroy the current Activity by default and create a new Activity and keep it in the state. The result is that Android re-loads the application UI from the resource. Now imagine that you have written an application with a very large bitmap, and you do not want to re-Load it every time you rotate it. The simplest way to keep it and do not reload it at each rotation is to save it on a static field:

Source code
 
 
  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("Leaks are bad");
  7. if (sBackground == null) {
  8. sBackground = getDrawable(R.drawable.large_bitmap);
  9. }
  10. label.setBackgroundDrawable(sBackground);
  11. setContentView(label);
  12. }

This code is very fast, and the error is outrageous. It exposes the first Activity created when the screen angle changes for the first time ). When a Drawable is appended to a View, this View is set as a callback of drawable. In the code snippet above, this means that this Drawable has a reference to TextView, and this TextView keeps reference to the Activity (Context object, at the same time, this Activity references a lot of objects (this amount depends on your code ).

This example is the simplest cause of Context leakage. You can check the source code on the home screen (view the unbindDrawables () method) this problem is solved by setting the saved Drawable callback to null when the Activity is destroyed. What's more interesting is that you can create a chain exposed by context. Of course, this is very bad. They allow you to quickly use up all the memory.

There are two simple methods to avoid Memory leakage related to context. The most obvious one is to avoid using context outside its own scope. The above example shows a static reference within the class and their indirect reference to the external class is very dangerous. The second solution is to use Application Context. This context exists along with your application and does not depend on the lifecycle of the Activity. If you want to keep an object that requires a long life cycle of context, consider the Application object. You can easily obtain it by calling Context. getApplicationContext () or Activity. getApplication.

To avoid Memory leakage involving context, remember the following points:

  1. Do not reference an Activity Context for a long life cycle (a reference to the Activity should be the same as the life cycle of the Activity itself)
  2. Try to use context-application instead of context-activity)
  3. If you cannot control their lifecycles, avoid using internal classes that are not static in the activity, use static classes, and use weak references to the activity. The solution to this problem is to use static internal classes and a weakreference external class. It is implemented just like viewroot and Its W internal class.
  4. The garbage collector is not guaranteed for Memory leakage.

Original article: Avoiding 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.