Android : References to a Context and memory leaks

。_饼干妹妹 提交于 2019-12-28 08:10:14

问题


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
    }
}

And call it from an Activity:

public class MyActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        HelperClass h = new HelperClass(this);
        h.myHelperMethod();
    }

    ...
}

回答1:


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.



回答2:


The scope of the HelperClass is only within your onCreate function, so once onCreate executed, your "h" object is no longer needed and subject to garbage collection.

It would be a different story if "h" was a static member - THAT would be a great way to leak memory.



来源:https://stackoverflow.com/questions/3346080/android-references-to-a-context-and-memory-leaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!