A common android Memory leakage problem

Source: Internet
Author: User
A common android Memory leakage problem

Recently, I checked the source code of a relatively large Android project in the company and found a very serious problem: the singleton mode is used in the project, and the constructor needs to input the context as the parameter class, basically, there is a memory leakage problem. I think no one has found any problems in this project, which should be quite common and serious at the same time.

Some code snippets with Memory leakage problems are as follows:

Util. Java

Public class util {

 

Private context mcontext;

Private Static util sinstance;

Private util (context ){

This. mcontext = context;

}

Public static util getinstance (context ){

If (sinstance = NULL ){

Sinstance = new util (context );

}

Return sinstance;

}

// Other methods

}

 

Suppose activity a uses the util class:

Util. getinstance (this );

 

The code is like this. In this case, the util class is used in activity A, and the incoming context is actvitiy-context. Imagine that when the lifecycle of activity a ends, but there is still a reference (mcontext) in the util class, so that the memory occupied by activity a cannot be recycled, and the object of a will not be used again. I have written code and tested it. In a, the finish () method is called, and the destroy () method of A is also executed, but the memory occupied by it, for example, the memory occupied by imageview, still cannot be released. If you are interested, test it yourself.

 

How can this problem be solved? In a, you can use util. getinstance (getapplicationcontext (); or util. getinstance (getapplication.

Because the life cycle of the application runs through the entire program, the util class holds its reference and will not cause memory leakage.

In fact, this question is a topic in the resources directory of the android official documentation.

Avoiding memory leaks

As mentioned in this article.

 

You can learn more by yourself.

 

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.