Original
In summary, 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 solution to this issue is to use a static inner class with aWeakReference to the outer class, as done in ViewRoot and its W inner class for instance
- A garbage collector is not an insurance against memory leaks
简而言之,为了避免和设备上下文导相关致的的内存泄露,请注意以下几点:
不要将一个生命期很长的引用关联到一个context-activity (因为对activity的引用将和activity 本身一样具有相同的生命周期)
使用context-application代替context-activity
避免非静态内部类在activity中,如果你没法控制他们的生命周期,使用一个静态内部类并且在里面使用一个对activity的弱引用。
垃圾回收期不能保证解决内存泄露。
source:http://android-developers.blogspot.tw/2009/01/avoiding-memory-leaks.html