Android avoid memory leaks

Time:2020-2-23

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.

 

Example:

Toast.makeText(MainActivity.this,"Hello",Toast.LENGTH_SHORT).show();

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.

resolvent?

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

Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();

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.