美文网首页
WeakReference一个应用

WeakReference一个应用

作者: lingnanlu | 来源:发表于2016-09-17 20:20 被阅读30次
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;
    private int data = 0;

    public BitmapWorkerTask(ImageView imageView) {
        // Use a WeakReference to ensure the ImageView can be garbage collected
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        data = params[0];
        return decodeSampledBitmapFromResource(getResources(), data, 100, 100));
    }

    // Once complete, see if ImageView is still around and set bitmap.
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}

当AsyncTask在执行过程中, 可能包含ImageView的Activity被销毁, 而ImageView又包含了Activity引用, 如果这里是强引用, 会导致Activity泄露。

相关文章

  • WeakReference一个应用

    当AsyncTask在执行过程中, 可能包含ImageView的Activity被销毁, 而ImageView又包...

  • WeakReference弱引用

    只有在 WeakReference weakReferencen=new WeakReference<>(new ...

  • WeakReference 在android中的应用

    首先我们来看一段代码 上面这段低吗没有什么问题,但是在handler对象创建的时候却会报警告:This Handl...

  • UI消息机制

    //WeakReference 弱引用,当WeakReference指向的对象是null时,gc就会回收这个对象p...

  • 对WeakReference的理解

    WeakReference让GC需要时回收对象 对于那些创建便宜但耗费大量内存的对象,即希望保持该对象,又要在应用...

  • LeakCanary分析

    WeakReference 被弱引用的对象当gc运行时会被回收这个构造方法构造的WeakReference,当被弱...

  • 不需要使用WeakReference来避免内存泄露

    原文地址:WeakReference in Android – Google Developers Experts...

  • Android WeakReference

    探讨一下为什么Android Studio会提示handler类要写成static的。 下面这张图是匿名内部类创建...

  • WeakReference简介

    WeakReference简介 什么是引用 首先要把引用和对象区别开来,比如Car car = new Car()...

  • C#弱引用(WeakReference)

    原文地址 :Part 1: Prefer WeakReference to WeakReferencePar...

网友评论

      本文标题:WeakReference一个应用

      本文链接:https://www.haomeiwen.com/subject/xgrwettx.html