安卓 : References to a Context and memory leaks

标签 android android-context

我了解到,在 Android 应用程序中保持对 Context 的长期引用是一个错误和内存泄漏的来源。

但我不明白是否可以创建一个看起来像这样的类:

public class HelperClass {
    private Context context;

    public HelperClass(Context context) {
        this.context = context;
    }
    public void myHelperMethod() {
        // uses this.context
    }
}

并从 Activity 中调用它:

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

    ...
}

最佳答案

这很好,不会导致内存泄漏。

一旦 onCreate 完成执行,h 将超出范围并符合垃圾回收条件。如果 h 是静态的,那么你会遇到问题。只有当对上下文的引用超过了上下文本身的生命周期时,才会发生内存泄漏。一些有用的提示:

  • 尽可能使用 Context.getApplicationContext()。只要您的应用程序存在,此上下文就会存在。
  • 使用静态字段和内部类时要小心。
  • Run your application through a profiler检查泄漏。

关于安卓 : References to a Context and memory leaks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3346080/

相关文章:

java - 使用 ViewHolder 为 ListView 项设置 onClickListener

java - 如何在 Android 中获取类(非 Activity )的上下文?

android - 图像未附加在 quickblox for android 中

java - 无法使用输入事件.Android

android - Android 中 Toast、数据库和其他实用程序的单例模式

android - 在 Presenter 类中访问 Actvity 的上下文是一种好习惯吗?如果没有,那么还有其他更好的方法吗?

android - 如何将上下文从一个 Activity 传递到另一个 Activity ?

android - MaterialComponents 中 AppCompat.Button.Borderless 的替代方案是什么?

java - 检测加载程序的 SQLite 数据库上的更改

android - Android Studio 是否有 Hierarchy Viewer 或 Layout Inspector?