为什么使用WeakReference Android侦听器?

前端之家收集整理的这篇文章主要介绍了为什么使用WeakReference Android侦听器?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在处理一个大的代码库,并在许多地方看到这种类型的代码
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以及几个具体的情况来避免:

> inner classes and leaks
> threads and leaks

原文链接:https://www.f2er.com/android/311080.html

猜你在找的Android相关文章