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 aContext parameter in their constructor. In a regular Android application, you usually have two kinds of ContextActivity andApplication. 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 aDrawable 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 the Home 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 calling Context.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 a WeakReference 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

Avoiding memory leaks的更多相关文章

  1. Avoiding memory leaks in POSIX thread programming, 多线程避免内存泄漏

    默认创建的线程为joinable的,必须调用pthread_join()才可以释放所占的内存 创建分离线程detach, attr 线程函数运行结束,调用pthread_exit 其它线程调用pthr ...

  2. On Memory Leaks in Java and in Android.

    from:http://chaosinmotion.com/blog/?p=696 Just because it's a garbage collected language doesn't mea ...

  3. [转]Activitys, Threads, & Memory Leaks

    转自:http://www.androiddesignpatterns.com/2013/04/activitys-threads-memory-leaks.html http://www.cnblo ...

  4. Identify Memory Leaks in Visual CPP Applications —— VLD内存泄漏检测工具

    原文地址:http://www.codeproject.com/Articles/1045847/Identify-Memory-Leaks-in-Visual-CPP-Applications 基于 ...

  5. 解决:Detected memory leaks

    最近在一个项目中,程序退出后都出现内存泄漏: Detected memory leaks!Dumping objects ->{171} normal block at 0x05785AD0, ...

  6. [Angular2 Router] Exiting an Angular 2 Route - How To Prevent Memory Leaks

    In this tutorial we are going to learn how we can accidentally creating memory leaks in our applicat ...

  7. The Introduction of Java Memory Leaks

    One of the most significant advantages of Java is its memory management. You simply create objects a ...

  8. 【转】简单内存泄漏检测方法 解决 Detected memory leaks! 问题

    我的环境是: XP SP2 . VS2003 最近在一个项目中,程序退出后都出现内存泄漏: Detected memory leaks! Dumping objects -> {98500} n ...

  9. _CrtSetBreakAlloc简单内存泄漏检测方法,解决Detected memory leaks!问题

    我的环境是: XP SP2 . VS2003 最近在一个项目中,程序退出后都出现内存泄漏: Detected memory leaks! Dumping objects -> {98500} n ...

随机推荐

  1. java常见问题集锦

    Eclipse 编译错误 Access restriction:The type *** is not accessible due to restriction on... 解决方案 Eclipse ...

  2. Laya Tween 和 遮罩

    Laya Tween 和 遮罩 @author ixenos 场景:在使用Tween循环时,不规则物体部分超出范围 方案:使用遮罩定型 困境:在laya ide设计模式中将遮罩sprite放到不规则物 ...

  3. java使用反射的好处

    文章:框架使用java反射好处 讲了框架读取配置文件的类名,使用反射灵活的创建对象.不用在代码层面写死,可以在一些场合非常灵活. 文章:Java 反射在实际开发中的应用 还没具体

  4. 洛谷P2527 [SHOI2001]Panda的烦恼

    题目描述 panda是个数学怪人,他非常喜欢研究跟别人相反的事情.最近他正在研究筛法,众所周知,对一个范围内的整数,经过筛法处理以后,剩下的全部都是质数,不过panda对这些不感兴趣,他只对被筛掉 ...

  5. 【转】SQL Server 创建约束图解 唯一 主键-界面操作

    SQL Server 创建约束图解 唯一 主键-界面操作 SQLServer中有五种约束,Primary Key约束.Foreign Key约束.Unique约束.Default约束和Check约束, ...

  6. 跳石头(codevs 4768)

    题目描述 Description 一年一度的“跳石头”比赛又要开始了! 这项比赛将在一条笔直的河道中进行,河道中分布着一些巨大岩石.组委会已经选择好了两块岩石作为比赛起点和终点.在起点和终点之间,有N ...

  7. 6572平台上关于wifi热点切换跳的坑

    最近在做一个无屏的项目,需要开启设备的wifi热点,通过连接热点设置设备wifi,本来看起来很容易完成的一件事情,遇到了一下的坑 在wifi切换状态时,大概率出现不能切换的问题,比如从wifi状态切换 ...

  8. [USACO08OPEN]牛的车Cow Cars

    题目描述 N (1 <= N <= 50,000) cows conveniently numbered 1..N are driving in separate cars along a ...

  9. PDO的基本操作

    PDO的基本操作 连接到mysql: try { $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); foreach($ ...

  10. ACM-ICPC 2018 徐州赛区网络预赛 D 杜教筛 前缀和

    链接 https://nanti.jisuanke.com/t/31456 参考题解  https://blog.csdn.net/ftx456789/article/details/82590044 ...