关于Picasso加载图片Callback不执行问题

问题背景

代码大致如下,Target或Callback的回调有时候不执行。

https://github.com/square/picasso/issues/352

第一种:使用Target

Picasso.get().load(URL).into(new Target() {
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        Log.i(TAG, "onBitmapLoaded: " + from);
    }

    @Override
    public void onBitmapFailed(Exception e, Drawable errorDrawable) {
        Log.e(TAG, "onBitmapFailed");
    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {
    }
});

第二种:使用Callback

ImageView imageView = new ImageView(this);
Picasso.get().load(URL).into(imageView, new Callback() {
    @Override
    public void onSuccess() {
        Log.i(TAG, "onSuccess: ");
    }

    @Override
    public void onError(Exception e) {
        Log.e(TAG, "onError" );
    }
});

以上代码,通常用在预加载图片的业务中。

问题原因

对于这样偶现的问题,第一反应应该是引用持有问题。果然,上述问题是弱引用问题: WeakReference
源码推导:

// 1.先看into方法:RequestCreator.java
public void into(@NonNull Target target) {
    // ...
    Action action =
        new TargetAction(picasso, target, request, memoryPolicy, networkPolicy, errorDrawable,
            requestKey, tag, errorResId);
    picasso.enqueueAndSubmit(action);
}

// 2.跟到Action:TargetAction.java
final class TargetAction extends Action<Target> {

  TargetAction(Picasso picasso, Target target, Request data, int memoryPolicy, int networkPolicy,
      Drawable errorDrawable, String key, Object tag, int errorResId) {
    // target被传到了super构造器
    super(picasso, target, data, memoryPolicy, networkPolicy, errorResId, errorDrawable, key, tag,
        false);
  }

  @Override 
  void complete(Bitmap result, Picasso.LoadedFrom from) {
    if (result == null) {
      throw new AssertionError(
          String.format("Attempted to complete action with no result!\n%s", this));
    }
    Target target = getTarget();
    if (target != null) { // 这一句判断很关键
      target.onBitmapLoaded(result, from);
      if (result.isRecycled()) {
        throw new IllegalStateException("Target callback must not recycle bitmap!");
      }
    }
  }

  @Override 
  void error(Exception e) {
    Target target = getTarget();
    if (target != null) { // 这一句判断很关键
      if (errorResId != 0) {
        target.onBitmapFailed(e, picasso.context.getResources().getDrawable(errorResId));
      } else {
        target.onBitmapFailed(e, errorDrawable);
      }
    }
  }
}

// 3.往上跟到Action的构造方法:Action.java
Action(Picasso picasso, T target, Request request, int memoryPolicy, int networkPolicy,
    int errorResId, Drawable errorDrawable, String key, Object tag, boolean noFade) {
// ...
this.target =
    target == null ? null : new RequestWeakReference<>(this, target, picasso.referenceQueue);
// ...
}

有此可见,如果this.target这个虚引用,要是在gc的时候被回收了,回调自然也不会有了。

场景复现

以下代码模拟系统内存紧张时候的gc过程,这样偶现问题便成了必现,或极大概率出现。

public void preloadImage() {
    Picasso.get().load(URL).into(new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            Log.i(TAG, "onBitmapLoaded: " + from);
        }

        @Override
        public void onBitmapFailed(Exception e, Drawable errorDrawable) {
            Log.e(TAG, "onBitmapFailed");
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
        }
    });

    for (int i = 0; i < 1000; i++) {
        double[] b = new double[1000000];
    }
    System.gc();
}

解决方式

可以考虑通过加持引用,不让若引用销毁。方式有很多种,这里可以考虑用匿名内部类来延长变量的生命周期。

第一种:使用Target

public void preloadImage() {
    Log.d(TAG, "preloadImage: preloadImage.");
    class Ref {
        private Target t;
    }
    final Ref ref = new Ref();
    ref.t = new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            Log.i(TAG, "preloadImage.onBitmapLoaded: " + from + ref.hashCode());
        }

        @Override
        public void onBitmapFailed(Exception e, Drawable errorDrawable) {
            Log.e(TAG, "preloadImage.onBitmapFailed" + ref.hashCode());
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
        }

        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            Log.e(TAG, "target.finalize!");
        }
    };
    Picasso.get().load(URL).into(ref.t);
}

第二种:使用Callback

public void preloadImage() {
    Log.d(TAG, "preloadImage: start.");
    final ImageView imageView = new ImageView(this);
    Picasso.get().load(URL).into(imageView, new Callback() {
        @Override
        public void onSuccess() {
            Log.i(TAG, "preloadImage.onSuccess: " + imageView.hashCode());
        }

        @Override
        public void onError(Exception e) {
            Log.e(TAG, "preloadImage.onError" + imageView.hashCode());
        }

        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            Log.e(TAG, "callback.finalize!");
        }
    });
}

以上。

版权声明:本文为chavin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/chavin/p/11420394.html