There are two easy ways to avoid context-related memory leaks.

1).The most obvious one is to avoid escaping the context outside of its own scope.

2).The second solution is 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() orActivity.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.


详情请见:http://developer.android.com/resources/articles/avoiding-memory-leaks.html

更多相关文章

  1. GitHub上不错的Android开源项目(二)
  2. 在GitHub平台上,究竟有哪些Android开源项目
  3. Android仿今日头条详情页实现
  4. 转载 Android仿今日头条详情页实现
  5. android 内存使用详情查询的几种方法
  6. Android仿“知乎”隐藏标题栏、回答详情页动画效果
  7. Android之——激活应用程序的详情界面
  8. 绿鹅等大厂2020Android面试经验(持续整理更新中)
  9. Android(安卓)html+动态添加控件,实现textview最后一行的显示效果

随机推荐

  1. android的调试技巧,尤其是nativec等底层程
  2. 如何让Android开机不锁屏
  3. [android深入学习]android窗口管理机制
  4. Android布局之baselineAligned属性
  5. android横竖屏备忘
  6. Android(安卓)学习路线图
  7. Delphi XE开发 Android(安卓)开机自动启
  8. Android应用程序中执行二进制命令
  9. Android push 极光通信
  10. Android Animation 框架