避免在Android的内存泄漏 [英] Avoid memory leaks on Android
问题描述
我刚刚看了一个博文由罗曼盖伊的关于如何避免在Android的内存泄漏。
I just read a blogpost by Romain Guy on how to avoid memory leaks in Android.
在文章中,他给出了这样的例子:
In the article he gives this example:
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 example is one of the simplest cases of leaking the Context.
我的问题是,你如何正确地修改了吗?
My question is, how do you modify it correctly?
就这样?
TextView label = new TextView(Context.getApplicationContext());
我测试两种方式,结果都是一样的。我无法找到的差异。我认为,这
比应用方面更正确。因为这
是参照活动
,也就是说,在的TextView
属于该活动
。
I tested both ways and the results are the same. I can't locate the difference. And I think that this
is more correct than the Application context. Because this
is a reference to Activity
, that is to say, the TextView
belongs to that Activity
.
可能有人给我一个解释吗?
Could someone give me an explanation for this?
推荐答案
与code中的实际问题不是通过创建绘制的背景下,但私有静态绘制对象sBackground; 静态绘制对象与活动的情况下创建的,所以在这种情况下,有一个静态引用绘制对象引用的活动,这就是为什么有泄漏。只要是引用存在,该活动将被保存在内存中,泄露其所有的意见。
The actual problem with that code isn't the context passed to create the drawable, but private static Drawable sBackground; The static Drawable is created with the Activity as the context, so in THAT case, there's a static reference to a Drawable that references the Activity, and that's why there's a leak. As long as that reference exists, the Activity will be kept in memory, leaking all of its views.
所以这是它应该使用的应用程序上下文,而不是TextView的创建的绘制对象。与创建TextView的本是完全没有问题。
So it's the Drawable which should be created using the application context, not the TextView. Creating the TextView with "this" is perfectly fine.
编辑:其实,这可能不会有很大的不同,问题是,一旦绘制被绑定到一个视图中,有一个参考的观点,它引用了活动。所以,你需要取消绑定的绘制当您退出活动。
edit : Actually, that might not make a big difference, the problem is that once the drawable is binded to a view, there's a reference to the view, which references the activity. So you need to "unbind" the drawable when you exit the activity.
这篇关于避免在Android的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!