Avoiding memory leaks ---- Context Leak 篇

Android —— 静态AsyncTask解决内存泄漏 Android中我们经常需要开启子线程去获取网络数据,或者说做一些耗时操作,开发者经常使用的就是AsyncTask,Android 1.5提供的工具类AsyncTask使我们创建异步线程更加便捷。如果你还没有AsyncTask的基础,那么先阅读一下这篇博文吧。 Android多线程编程(异步通信)—>Handler和AsyncTask本博文编写的理由: 线程的关闭,可以通过在activity的d 阅读详情

原文地址:http://android-developers.blogspot.tw/2009/01/avoiding-memory-leaks.html


Android applications are, at least on the T-Mobile G1, limited to 16 MB of heap. It's both a lot of memory for a phone and yet very little for what some developers want to achieve. Even if you do not plan on using all of this memory, you should use as little as possible to let other applications run without getting them killed. The more applications Android can keep in memory, the faster it will be for the user to switch between his apps. As part of my job, I ran into memory leaks issues in Android applications and they are most of the time due to the same mistake: keeping a long-lived reference to a Context.

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. It's usually the first one that the developer passes to classes and methods that need a Context:

@Override
protected void onCreate(Bundle state) {
  super.onCreate(state);
  
  TextView label = new TextView(this);
  label.setText("Leaks are bad");
  
  setContentView(label);
}

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. Therefore, if you leak the Context ("leak" meaning you keep a reference to it thus preventing the GC from collecting it), you leak a lot of memory. Leaking an entire activity can be really easy if you're not careful.

When the screen orientation changes the system will, by default, destroy the current activity and create a new one while preserving its state. In doing so, Android will reload the application's UI from the resources. Now imagine you wrote an application with a large bitmap that you don't want to load on every rotation. The easiest way to keep it around and not having to reload it on every rotation is to keep in a static field:

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);
}

This code is very fast and also very wrong; it leaks the first activity created upon the first screen orientation change. When a Drawable is attached to a view, the view is set as a callback on the drawable. In the code snippet above, this means the drawable has a reference to the TextView which itself has a reference to the activity (the Context) which in turns has references to pretty much anything (depending on your code.)

This example is one of the simplest cases of leaking the Context and you can see how we worked around it in theHome screen's source code (look for the unbindDrawables() method) by setting the stored drawables' callbacks to null when the activity is destroyed. Interestingly enough, there are cases where you can create a chain of leaked contexts, and they are bad. They make you run out of memory rather quickly.

There are two easy ways to avoid context-related memory leaks. The most obvious one is to avoid escaping the context outside of its own scope. The example above showed the case of a static reference but inner classes and their implicit reference to the outer class can be equally dangerous. 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 callingContext.getApplicationContext() or Activity.getApplication().

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

避免 Android中Context引起的内存泄露 Context是我们在编写Android程序经常使用到的对象,意思为上下文对象。 常用的有Activity的Context还是有Application的Context。Activity用来展示活动界面,包含了很多的视图,而视图又含有图片,文字等资源。在Android中内存泄露很容易出现,而持有很多对象内存占用的Activity更加容易出现内存泄露,开发者需要特别注意这个问题。 本文讲介绍Android中Context,更具体的说是Activity内存泄露的情况,以及如何避免Activity内存泄露,加速应用性能。 Drawable引起的内存泄露 Drawable引起内存泄露这个问题是比较隐晦, 立即下载

相关推荐

车载测试面试题总结

首先确认是什么问题,如果是测试软件的问题就先确定自己的测试方法有没有问题,如果没有问题,那就是测试软件的问题,这时候就需要提bug 进行跟踪,(比如BCM测试的时候,先明确测试的输入,对输入)进行需求分析,然后设计测试用例,进行用例评审,评审完执行测试用例形成最终的版本,台架分为:hil(黑尔)台架,单个控制器的台架、整车台架、车身台架、动力系统台架等,主要验证其功能,或者实车无法满足的测试环境。这个人不可能一直,点击几千次或者多少次几个小时连续点击,人不可能一直在点。因为要模拟一下这个稳定性,

woaxiaoqing的博客 7817

Android上下文对象this,此字段泄漏上下文对象 - This field leaks a context object - 开发者知识库...

10You assign a View to your HttpRequestTask. Since a View requires a Context you are leaking it.将视图分配给HttpRequestTask。由于视图需要上下文,所以您正在泄漏它。Just think what happen if the View has been destroyed but the H...

weixin_32259717的博客 763

FusionCompute8.0.0实战指南:从零部署CNA与VRM环境

本文以华为FusionCompute 8.0.0为例,详细介绍了如何利用老旧硬件从零开始部署CNA计算节点与VRM管理节点的完整实战指南。内容涵盖实验环境准备、CNA安装与网络配置、VRM虚拟机部署方案对比,并提供了典型故障排查与性能调优技巧,帮助读者低成本构建可用的虚拟化学习环境。

weixin_29306317的博客 315

AsyncTask内存泄漏的问题及处理办法

This field leaks a context object less... (Ctrl+F1) A static field will leak contexts. Non-static inner classes have an implicit reference to their outer class. If that outer class is for example a...

彭辛乾的专栏 2741

cvtColor +内存泄漏

题目不知道怎么取,因为cvtColor并没有产生内存泄漏,但是我由于没有正确使用cvtColor而出现了内存泄漏的问题,所以暂且以cvtColor+内存泄漏为题 1.应用背景 项目中用到cvtColor的地方是需要将灰度图转为3通道的彩色图(实际上转换后仍然为灰色的,但是电脑认为的是3通道的彩色图了) 因此需要用到以下语句 cvtColor(src_img, cvMtxRGB, C

smilebluesky的专栏 6058

支付漏洞防护绕过的一种方式

放完包后就到了提交订单的地方,可以发现,金额确实小了很多,合理的搭配的话还可以更低,再次前进可以发现,金额确实是这么多,后面就不支付了,到此就结束了。也就是说数量可以为负数,但是金额不能为0或者0以下,有什么方法可以绕过这个限制吗,其实并不难,既然可以为负数,只是对金额不能为0或者负数做了限制。我们可以尝试拼接法,利用负数加上正数让他的值变得很低,但是又大于0就可以了,这里利用购物车的结算方法,随机加一些在购物车里。这里为了方便查看数据包,我这边商品的数量选择3,点击立即购买并抓包。

2301_80115097的博客 1529

Android开发——避免内存泄露

Android开发——避免内存泄露 本文翻译自Avoiding memory leak——Post by Romain Guy 著作权归原作者所有。转载请注明出处,由JohnTsai翻译 Android应用被分配的堆的大小限制为16MB。这对于手机来说已经很多了,但对于一些开发者想获得的来说仍旧不够。即使你没有计划使用所有的这些内存。你应该尽可能的少用以避免其他应用在运行时因为内存不足...

didingyun4257的博客 229

避坑指南:汇川SV660N配合SOEM时,PDO映射与CiA402状态机那些容易出错的地方

本文深入解析汇川SV660N伺服驱动与SOEM主站在PDO动态映射和CiA402状态机切换中的常见问题,提供实战代码和调试技巧。重点解决PDO配置时序、状态机转换同步等关键难点,帮助工程师避免典型错误,实现稳定通信与控制。

weixin_30653023的博客 498

Avoiding memory leaks

http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html Avoiding memory leaks Posted by Romain Guy on 19 January 2009at10:09 PM Android applications are, at least on the

FrancisLeeTang的专栏 627

TTL转RS422(B)工业级转换模块设计:从原理到实战部署

在工业自动化与嵌入式系统中,串行通信是实现设备间数据交换的基础。其核心原理在于通过特定的电气标准与协议,将数据位序列化后进行传输。RS422作为一种差分平衡传输协议,相比常见的TTL电平,在抗共模干扰与远距离传输能力上具有显著的技术优势,这使其成为工业现场总线、楼宇自动化等对可靠性要求严苛场景的优选方案。要实现TTL设备与RS422网络的稳定互联,关键在于设计一个能够完成单端信号到差分信号高质量转换的硬件模块。这涉及到差分总线收发器芯片的选型、包含终端电阻与TVS二极管的保护电路设计,以及遵循差分走线规则的

weixin_29195615的博客 342

【乐企文件生成工程】关于乐企文件生成工程的详细介绍

发票文件生成方式有两种思路:1、根据已有的OFD模板,动态替换ofd模板内容;之后将ofd转pdf(局限:单行问题不大)详情可以在此处了解2、根据html模板动态占位:该工程就是这种方式 ,目前效果良好,可看下图。拿去即用的源码!无任何保留,当然也并不是所有票种都支持(时间有限、精力有限、已经连着转了,要冒烟了…)

九七的博客 2031

Android articles 翻译之一:Avoiding Memory Leaks

Avoiding Memory LeaksAndroid applications are, at least on the T-Mobile G1, limited to 16 MB of heap. It's both a lot of memory for a phone and yet very little for what some developers want to achieve. Even if you do not plan on using all of this memory

康康兔的牛棚 958

GEE APP:基于Sentinel-1 SAR数据的洪水检测与制图系统:利用GEE平台实现洪涝区域提取、面积统计及矢量栅格化导出

本文介绍了一个基于Google Earth Engine平台的Sentinel-1 SAR洪水监测应用,通过自动化流程实现洪水淹没区域的精准检测与分析。系统采用Refined Lee滤波降噪和Otsu自适应阈值算法,结合SRTM地形数据消除干扰,可自动计算淹没面积并生成可视化结果。该工具提供用户友好的交互界面,支持多格式数据导出,适用于灾害应急响应、环境监测和城市规划等领域,具有云平台处理、算法鲁棒性强和操作简便等技术优势。

此星光明博客 327

【翻译】Android避免内存泄露(Activity的context 与Context.getApplicationContext)

原谅地址:http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html,英文原文在翻译之后 Android 应用至少,在T-Mobile G1这个型号,就有16MB的堆内存。这个容量对于手机来说是很大了,但是对于有些开发者来说是少了些。为了全其他应用可以运行而不被系统杀掉,即使你没有打算使用完所有分配的容量,...

weixin_30340617的博客 126

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

一个常见的android内存泄露 问题

最近在看一个算比较大的android项目的源码,发现了一个很严重的问题,就是项目里使用单例模式,构造函数要传入Context做参数的类,基本上都存在内存泄露问题。     存在内存泄露问题的一些代码片段像下面这样: Util.java public class Util { private Context mContext; private static Util sIns...

bcf 203

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Android的Context泄露分析和解决方案

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34249367的博客 535

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

使用AsyncTask防止Memory Leaks(内存泄漏)的正确姿势

1:合理的使用context–比如我们常使用的Toast,Service,最好使用getApplicationContext(),因为这些在activity结束的时候可能仍在运行 下图展示了一些场景我们该用哪种context(图是盗的,附原文地址https://possiblemobile.com/2013/06/context/ 是国外的大牛写的关于context的使用)2:不要在activ

春暖花自开 6955

解释context memory leak的文章

http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html The "static" keyword has different meanings when it comes to "static variables" vs. "static classes" in Java. A ...

ycljf86 234

(翻译)avoiding memory leaks

原文来自Android SDK文档中的 docs/resources/articles/avoiding-memory-leaks.html   android应用,堆内存大小限制为16MB(至少在T-Mobile G1上是这样)。 对手机而言, 这已经是相当大一部分内存,但对某些开发者而言16MB太少了。 就算不准备使用全部的16MB内存, 至少也应用使用尽可能少的内存,从而避免其他应用因...

chen_410063005的专栏 202

Context 使用不当造成内存泄露

问题:   Activity中的context被传递给了一个生命周期长过activity的对象(通常为静态单实例变量),导致activity不能正常被销毁。   示例:Activity 调用 ChatMgr 时将context传递进来,由于ChatMgr为单实例对象,context被引用,导致Activity退出时无法销毁。见代码: public static ChatMg...

150

解决AsyncTask的线程池限制问题

这是一篇我个人在EOE发的帖子《解决AsyncTask的线程池限制问题》,由于eoe的blog系统实在是无言以对,我就把eoe上面的帖子以及blog是都转到csdn上来,原帖地址:http://www.eoeandroid.com/thread-329718-1-1.html 大家如果有使用到AsyncTask的话,应该会了解到AsyncTask固然好用,但是它本身设计了对于线程池的

lsmfeixiang的专栏 3036

1.8.x的新修复解决了内存泄漏问题并改进了性能

就性能而言,目前Ruby 1.9.1和JRuby领导着Ruby的实现。然而由于种种原因,转到这两个实现中的任何一个都不是那么容易的事情,因为Ruby 1.9.x在有些地方与1.8.7不兼容,同时JRuby仍旧缺乏一些使用本地扩展的Ruby库。由于这个原因,MRI 1.8.x还会继续存在一段时间,那么我们可能对其性能的改进产生兴趣。\u0026#xD;\n目前Brent Roman在一定程度上改进了...

啊啊啊啊2 316

avoid memory leak in osip

I was debugging memory leak bugs recently. The bug was caused by incorrect usage of the osip library. It's not uncommon that we meet problems when we rely on a library or framework that we don't fully understand. Symptom and debugging The symptom is our

just do IT 644

警告:Spring ApplicationContext - Resource leak: 'context' is never closed的处理

在一次代码调试中,发现了一条Warning提示: Spring ApplicationContext - Resource leak: ‘context’ is never closed. 这是什么意思?

梅森上校的博客 业精于勤荒于嬉,形成于思毁于随。 8146
上一篇: 关于Surface,Window,View,SurfaceView,Bitmap的理解
下一篇: Android IPC 进程间通信实现理解
AnnaLoad
博客等级 码龄17年 7粉丝 23原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值