我刚刚阅读了Romain Guy的一篇博客文章,讲述如何避免在Android中出现内存泄漏。
在文章中,他给出了以下示例:
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);
}
Romain说:
这个示例是泄漏Context的最简单情况之一。
我的问题是,你如何正确地修改它?
就像这样?
TextView label = new TextView(Context.getApplicationContext());
我测试了两种方式,结果都相同。我找不到差异。而且我认为this
比应用程序上下文更正确。因为this
是对Activity
的引用,也就是说TextView
属于该Activity
。
有人能给我解释一下吗?