Check and Avoid Memory Leaks in Application

2019-03-10 02:52发布

问题:

So, I am done with a project, now the main issue I am facing is the Memory Leakage in the application (“leak” meaning you keep a reference to an activity, thus preventing the GC from collecting it)

Some of the cases I found, where the memory leakage occurs are:

Context Leakage

It occurs because of long lived reference to the activity context.

A very good example of it i found here,

private static Drawable sBackground;

@Override
protected void onCreate(Bundle state) {
  super.onCreate(state);

  TextView label = new TextView(this);
  label.setText("Leaks are bad");

  if (sBackground == null) {
    sBackground = getDrawable(R.drawable.large_bitmap);
  }
  label.setBackgroundDrawable(sBackground);

  setContentView(label);
}

here the problem is with private static Drawable sBackground; The static Drawable is created with the Activity as the context, so in THAT case, there's a static reference to a Drawable that references the Activity, and that's why there's a leak. As long as that reference exists, the Activity will be kept in memory, leaking all of its views.

Screen orientation change

The second case that draws the attention is when the screen orientation changes. When the screen orientation changes the system will, by default, destroy the current activity and create a new one while preserving its state. In doing so, Android will reload the application’s UI from the resources. Now imagine you wrote an application with a large bitmap that you don’t want to load on every rotation.

This will result in a lot of memory leakage as there could be large bitmaps to load.

context-activity

The third case, I found was the reference to the activity context. It also results in memory leakage.

I wonder if there is any easy way to avoid such memory leakages from happening. or if there could be tool to check and remove those memory leakages from the application.

回答1:

you can use tools like traceview or memory analyzer to check for memory leaks

http://developer.android.com/tools/help/traceview.html

http://kohlerm.blogspot.com/2009/04/analyzing-memory-usage-off-your-android.html

Here are some articles i found helpful

http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html

http://vahidmlj.blogspot.com/2012/10/android-memory-leak-on-screen-rotation.html



回答2:

I know this is an old post, but recently Square released a library called LeakCanary which is by far the most elegant solution for finding memory leaks.