Android:对上下文和内存泄漏的引用 [英] Android : References to a Context and memory leaks
问题描述
我已经读到,在 Android 应用程序中保持对 Context 的长期引用是一个错误和内存泄漏的来源.
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 a 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
}
}
并从活动中调用它:
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.
一旦 onCreate
完成执行,h
将超出范围并有资格进行垃圾回收.如果 h
是静态的,那么你会遇到问题.只有当对上下文的引用超过上下文本身的生命周期时,才会发生内存泄漏.一些有用的提示:
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:
- 尽可能使用
Context.getApplicationContext()
.只要您的应用程序还活着,这个上下文就会一直存在. - 使用静态字段和内部类时要小心.
- 通过分析器运行您的应用程序 检查是否有泄漏.
- 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.
这篇关于Android:对上下文和内存泄漏的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!