SoFunction
Updated on 2025-03-01

Talk about Android memory leak problem

Memory leak: refers to the timely recycle of memory by GC, which causes excessive memory usage, which leads to program Crash, which is commonly known as OOM.
1. Static
Let's take a look at the following code

public class DBHelper {

  private static DBHelper db= null;

  private DBHelper() {

  }

  public static DBHelper getInstance(Context context) {
    if (bitmapUtils == null) {
      synchronized () {
        if (db== null) {
          db= new db(context,DBNAME);

        }
      }
    }
    return db;
  }
}

Such code is very common in projects. If you are careful, you should find out where the problem lies. The helper holds the context application, and DBHelper is global. That is to say, when DBHelper is used in an activity, even if the activity exits, the activity cannot be recycled by GC, resulting in the activity resides in memory all the time.
This solution is also relatively simple, the code is as follows

public class DBHelper {

  private static DBHelper db= null;

  private DBHelper() {

  }

  public static DBHelper getInstance(Context context) {
    if (bitmapUtils == null) {
      synchronized () {
        if (db== null) {
          db= new db((),DBNAME);

        }
      }
    }
    return db;
  }
}

Just change the context to ApplicationContext(), because ApplicationContext itself is global.
2. Non-static internal classes, Handlers
Let's take a look at a piece of code first

  private Handler handler = new Handler(){
    @Override
    public void dispatchMessage(Message msg) {
      // Message processing    }
  };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_main);
    new Thread(new Runnable() {

      @Override
      public void run() {
        // Time-consuming operation        (1);
      }
    }).start();
  }

We know that non-static inner classes will hold references to external classes. At this time, the Handler here holds references to external Activity. When we perform asynchronous time-consuming operations in the Activity inner class, if our Activity is finished at this time and the asynchronous task does not end, this will cause our Activity object to be recycled by GC in time, resulting in memory problems.
SuchProblem solvingIt's very simple to be

  • Do not perform asynchronous operations in anonymous internal classes
  • Using static anonymous internal classes

Most memory problems are caused by accidental processing of the object's life cycle. When using an object, we need to carefully study the life cycle of the object. When processing some objects that occupy large memory and have a long life cycle, the application uses soft references to process it and close unused resources in a timely manner.

The above is all about this article, I hope it will be helpful to everyone's learning.