安卓:引用到上下文和内存泄漏 [英] Android : References to a Context and memory leaks
问题描述
我已经读,这是一个错误,内存泄漏源在Android应用程序,以保持一个长期存在引用的上下文。
但我不明白,如果它是确定创建一个看起来像这样的一个类:
公共类助手类{
私人上下文的背景下;
公共助手类(上下文的背景下){
this.context =背景;
}
公共无效myHelperMethod(){
//使用this.context
}
}
和从活动中调用它:
公共类MyActivity延伸活动{
公共无效的onCreate(包savedInstanceState){
助手类H =新助手类(本);
h.myHelperMethod();
}
...
}
这是好的,并不会造成内存泄漏。
当的onCreate
执行完毕, ^ h
将超出范围并符合垃圾收集。如果 ^ h
是静态的,那么你会遇到问题。仅当参考上下文会超越的上下文的生命周期本身将内存泄漏发生。一些有用的提示:
- 使用
Context.getApplicationContext()
在可能的情况。这种情况下将生活,只要你的应用程序是活的。 - 在使用静态字段和内部类时要小心。
- 通过探查检查运行应用程序泄漏。
I've read that it is a mistake and a source of memory leaks in Android application to keep a long-lived references to a Context.
But I don't understand if it is ok to create an class that looks like this one:
public class HelperClass {
private Context context;
public HelperClass(Context context) {
this.context = context;
}
public void myHelperMethod() {
// uses this.context
}
}
And call it from an Activity:
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
HelperClass h = new HelperClass(this);
h.myHelperMethod();
}
...
}
This is fine, and will not cause a memory leak.
As soon as onCreate
finishes executing, h
will be out of scope and become eligible for garbage collection. If h
was static, then you would run into problems. Only when the reference to the context outlives the lifecycle of the context itself will a memory leak occur. A few helpful hints:
- Use
Context.getApplicationContext()
when possible. This context will live as long as your application is alive. - Be careful when using static fields and inner classes.
- Run your application through a profiler to check for leaks.
这篇关于安卓:引用到上下文和内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!