Android avoid memory leaks


What is a memory leak?

It is the memory that has not been recycled for various reasons and still resides in the memory.

What is the impact of a memory leak?

A small memory leak may cause the whole application to jam or even crash.




This code may leak memory.

Why is it possible to cause memory leaks?

If toast holds the current activity before it disappears, and at this time, the user clicks the return key, resulting in the activity cannot be recycled by GC (garbage collection), which causes memory leak.


All contexts unrelated to the current activity can be passed in. The method to avoid memory leakage also uses other places where the context needs to be passed in. (I can’t understand this sentence) here’s how


Getapplicationcontext() is the context of the entire application and does not hold an activity object.


Be careful

The context of dialog cannot use getapplicationcontext(), and the program will crash. The dialog instantiation must hold the activity object.