2011年3月20日 星期日

[Resources] Avoiding Memory Leaks

* Most of the time due to the same mistake to memory leaks: keeping a long-lived reference to a Context.

* A Context is used for many operations but mostly to load and access resources. In a regular Android application, you usually have two kinds of Context, Activity and Application.

* This means that views have a reference to the entire activity and therefore to anything your activity is holding onto; usually the entire View hierarchy and all its resources.

* There are two easy ways to avoid context-related memory leaks.
  1. To avoid escaping the context outside of its own scope.
  2. To use the Application context. This context will live as long as your application is alive and does not depend on the activities life cycle.

* If you plan on keeping long-lived objects that need a context, remember the application object. You can obtain it easily by calling Context.getApplicationContext() or Activity.getApplication().

* In summary, to avoid context-related memory leaks, remember the following:
  1. 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)
  2. Try using the context-application instead of a context-activity.
  3. 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 a WeakReference to the outer class, as done in ViewRoot and its W inner class for instance
  4. A garbage collector is not an insurance against memory leaks



* Reference
- Avoiding Memory Leaks

沒有留言:

張貼留言