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.