Thursday, January 22, 2015

How to avoid MEMORY LEAKS in Android

Memory leaks means resources which are not available for garbage collection. GC will free resources which are not referenced. Sometimes a single reference can prevent a large set of objects from being garbage collected. For example, some static variables which are referenced in an activity may not be for GC, because as long as the reference exists, the Activity will be kept in memory, leaking all of its views.

Code snippet from Romain Guy is as,

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 static drawable sBackground will leak.

The solution here is when the activity gets destroyed, release the drawable in destroy and unbind all callbacks


Here, our onDestroy() will look like this,


protected void onDestroy() { 
super.onDestroy();
sBackground.setCallbacks(null);
sBackground = null;
}

So that the drawable sBackground will be available for GC and can prevent memory leak when activity gets destroyed.

Another common cause for memory leak is non-static inner classes in an Activity. This commonly comes when creating fragments in an Activity. Either create static inner classes or create stand alone classes.

Reference:
http://android-developers.blogspot.in/2009/01/avoiding-memory-leaks.html
http://stackoverflow.com/questions/6567647/avoid-memory-leaks-on-android

No comments:

Post a Comment

Androidians