What is memory leak and how to avoid it?

Copied from https://stackoverflow.com/questions/6567647/avoid-memory-leaks-on-android http://www.curious-creature.com/2008/12/18/avoid-memory-leaks-on-android/

“leak” meaning you keep a reference to it thus preventing the GC from collecting it.

On Android, a Context is used for many operations but mostly to load and access resources. This is why all the widgets receive a Context parameter in their constructor. In a regular Android application, you usually have two kinds of Context, Activity and Application.

避免内存泄漏的方法 to avoid context-related memory leaks, remember the following:

  • Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)

  • Try using the context-application instead of a context-activity

  • Avoid non-static inner classes in an activity if you don’t control their life cycle, use a static inner class and make a weak reference to the activity inside

造成内存泄漏的原因 the problem is that once the drawable is bound to a view, there's a reference to the view, which references the activity. So you need to "unbind" the drawable when you exit the activity.