android - 为什么在 Android Listeners 上使用 Wea​​kReference?

标签 android weak-references

我正在处理一个大型代码库,并且在很多地方看到这种类型的代码:

public static class RequestCustomData implements View.OnClickListener {
    WeakReference<MainActivity> mainActivity;

    public RequestCustomData(MainActivity activity) {
        mainActivity = new WeakReference<>(activity);
    }

    @Override
    public void onClick(View view) {
        MainActivity activity = mainActivity.get();
        activity.requestCustomData(true, null);
    }
}

我有点疑惑为什么这么多地方用到这个?我查看了这份文档,但它并没有很好地阐明为什么这种类型的代码在我正在开发的应用程序中如此频繁地使用

https://community.oracle.com/blogs/enicholas/2006/05/04/understanding-weak-references

如果这是一种常见模式,谁能给我解释一下?如果是,为什么?

最佳答案

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory.

如果 RequestCustomData 对象的生命周期可能超过 Activity 本身,则此代码的作者很可能希望避免泄漏 Activity 上下文。

我推荐Romain Guy's post on this topic以及要避免的几种特定情况:

关于android - 为什么在 Android Listeners 上使用 Wea​​kReference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36191755/

相关文章:

android - 无法在 Android Studio 中编译 exoplayer

java - 编辑文本属性不显示日期

java - Android IabHelper 检查是否购买

c++ - 在 C++ 中实现弱侵入指针

android - Bitmap、Bitmap.recycle()、WeakReferences 和垃圾回收

java - 如果值包含对键的唯一强引用,是否会收集 WeakHashMap 的条目?

ios - MVVM:使用闭包、无主或弱 self 将 View 与 ViewModel 绑定(bind)?

android - 如何使用android读取json中的属性值

android - 什么是 com.google.android.apps.nbu.files.provider/2?

swift - iOS 数据源和导出引用