为什么在 android 个监听器上使用 Wea​​kReference?

why use WeakReference on android Listeners?

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

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 以及要避免的几种特定情况: