Picasso加载一张图片的具体过程

Picasso

一般我们在使用Picasso加载图片时,会进行如下代码所示进行调用:

Picasso.with(this).load("http://i.imgur.com/DvpvklR.png").into(img);

然而这背后的都是如何处理的呢?下面我们就一步步来看看Picasso库是如何调用来显示一张图片到我们手机界面上的?

(1)Picasso.with(this)方法———得到Picasso对象

我们先来看一下Picasso.with(this)方法的源代码:

public static Picasso with(Context context) {
    if (singleton == null) {
      synchronized (Picasso.class) {
        if (singleton == null) {
          singleton = new Builder(context).build();
        }
      }
    }
    return singleton;
  }

从上面代码可以看出这里利用单例的设计模式来返回一个单例对象(Picasso),这里的关键点变成了 Builder(context).build()是如何构造Picasso对象的问题了?

1.1 Builder(context).build()———-返回Picasso实例

下面,我们接着来看一下build()方法的源码:

public Picasso build() {
      Context context = this.context;

      if (downloader == null) {
        downloader = Utils.createDefaultDownloader(context); //创建默认的下载器
      }
      if (cache == null) {
        cache = new LruCache(context);//初始化缓存
      }
      if (service == null) {
        service = new PicassoExecutorService();
      }
      if (transformer == null) {
        transformer = RequestTransformer.IDENTITY;
      }

      Stats stats = new Stats(cache);

      Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);

      return new Picasso(context, dispatcher, cache, listener, transformer, requestHandlers, stats,
          defaultBitmapConfig, indicatorsEnabled, loggingEnabled);
    }

上面代码中首页根据Utils.createDefaultDownloader(context)方法来创建默认的图片下载器;然后创建LruCache()对象用来缓存图片,PicassoExecutorService()对象用来执行下载任务,RequestTransformer是用来设置图片变换的(例如:圆形,圆角显示图片等);Stats用来记录cache缓存的状态;Dispatcher用来进行相关事件的分发器(如:开始下载图片,图片下载完成等);在方法的最后,返回一个Picasso的实例对象来供下步的调用使用!因此可以看出经过Picasso.with(this)方法我们得到了一个Picasso的对象。
看完了Picasso.with(this)方法,下面我们来学习一下load(path)方法,看看在这个方法又做了什么有趣的事情?

(2)load(path)方法———得到RequestCreator对象

  • 接下来我们一起来探究一下Picasso类load()方法的源码:
public RequestCreator load(String path) {
    if (path == null) {
      return new RequestCreator(this, null, 0);
    }
    if (path.trim().length() == 0) {
      throw new IllegalArgumentException("Path must not be empty.");
    }
    return load(Uri.parse(path));
  }

在这个方法,首先判断若传入的参数为空,则会创建一个RequestCreator对象,若参数不为空,则会调用load(Uri.parse(path))方法。

下面我们需要看一下load(Uri.parse(path))方法的源码,我们继续进入这个方法:

public RequestCreator load(Uri uri) {
    return new RequestCreator(this, uri, 0);
  }

在这个方法中会根据path解析的uri来创建一个RequestCreator对象。有的人会问?这个对象有什么作用了?
其实个这对象就是创建一个图片的下载请求。
看完了load(path)方法,下面我们接着来学习一下into()方法,看看在这个方法又做了什么有趣的事情?

(3)into() ————-开始下载图片及显示图片

由于(2)load(path)了RequestCreator对象,因此,我们需要进入 ### RequestCreator###类的into()方法来look一下,其源码如下:

public void into(ImageView target, Callback callback) {
    long started = System.nanoTime();
    checkMain(); //主线程检查,不在主线程会抛异常

    if (target == null) {
      throw new IllegalArgumentException("Target must not be null.");
    }
    //如果设置过了图片
    if (!data.hasImage()) {
      //取消请求
      picasso.cancelRequest(target);
      //设置占位图片
      if (setPlaceholder) {
        setPlaceholder(target, getPlaceholderDrawable());
      }
      return;
    }

    //如果设置了fit()
    if (deferred) {
      if (data.hasSize()) {
        throw new IllegalStateException("Fit cannot be used with resize.");
      }
      int width = target.getWidth();
      int height = target.getHeight();
      if (width == 0 || height == 0) {
        if (setPlaceholder) {
          setPlaceholder(target, getPlaceholderDrawable());
        }
        picasso.defer(target, new DeferredRequestCreator(this, target, callback));
        return;
      }
      //重新设置宽高
      data.resize(width, height);
    }
    //创建http请求
    Request request = createRequest(started);
    //创建请求对应的关键字
    String requestKey = createKey(request);

    //查看是否可从缓存中读取图片
    if (shouldReadFromMemoryCache(memoryPolicy)) {
      //根据请求key来从缓存中获取Bitmap对象
      Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
      if (bitmap != null) {
        //取消网络请求
        picasso.cancelRequest(target);
        //设置从缓存中读取的Bitmap到Imageview控件上
        setBitmap(target, picasso.context, bitmap, MEMORY, noFade, picasso.indicatorsEnabled);
        if (picasso.loggingEnabled) {
          log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), "from " + MEMORY);
        }
        if (callback != null) {
          callback.onSuccess();
        }
        return;
      }
    }
    //设置占位图片
    if (setPlaceholder) {
      setPlaceholder(target, getPlaceholderDrawable());
    }

    Action action =
        new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
            errorDrawable, requestKey, tag, callback, noFade);

    picasso.enqueueAndSubmit(action);
  }

由于这个方法过长,我就不细说了,我已经在源码中加入了注释,感兴趣的同还可以看一下!我们定位到方法的最后两句代码,这两句代码创建一个ImageViewAction对象并通过enqueueAndSubmit(action)方法,把图片的请求进入队列并进行提交,因此,我们需要进入Picasso的enqueueAndSubmit这个方法来了解一下,其源码如下:

void enqueueAndSubmit(Action action) {
    Object target = action.getTarget();
    if (target != null && targetToAction.get(target) != action) {
      // This will also check we are on the main thread.
      cancelExistingRequest(target);
      targetToAction.put(target, action);
    }
    submit(action); //调用下面的方法
  }

  void submit(Action action) {
    dispatcher.dispatchSubmit(action);
  }

上面第一个方法在最后调用了第二个方法,经过上面这两个方法的调用,最后进入分发器的分发提交方法,其Dispathcer中dispathchSubmit(action)方法源码如下:

 //发送handler消息调用下面的方法
 void dispatchSubmit(Action action) {
    handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
  }
  //这个方法又调用了下面的方法
  void performSubmit(Action action) {
    performSubmit(action, true);
  }

  void performSubmit(Action action, boolean dismissFailed) {
    //查看是否需要暂停请求
    if (pausedTags.contains(action.getTag())) {
      pausedActions.put(action.getTarget(), action);
      if (action.getPicasso().loggingEnabled) {
        log(OWNER_DISPATCHER, VERB_PAUSED, action.request.logId(),
            "because tag '" + action.getTag() + "' is paused");
      }
      return;
    }

    //查看是否在Bitmap的请求map是否有本次请求
    BitmapHunter hunter = hunterMap.get(action.getKey());
    if (hunter != null) {
      hunter.attach(action);
      return;
    }

    if (service.isShutdown()) {
      if (action.getPicasso().loggingEnabled) {
        log(OWNER_DISPATCHER, VERB_IGNORED, action.request.logId(), "because shut down");
      }
      return;
    }
    //创建BitmapHunter的请求Runnable,在线程中进行网络请求
    hunter = forRequest(action.getPicasso(), this, cache, stats, action);
    //把BitmapHunter放入线程池进行请求执行
    hunter.future = service.submit(hunter);
    hunterMap.put(action.getKey(), hunter);
    if (dismissFailed) {
      failedActions.remove(action.getTarget());
    }

    if (action.getPicasso().loggingEnabled) {
      log(OWNER_DISPATCHER, VERB_ENQUEUED, action.request.logId());
    }

在上面这几个方法中最后会调用到service.submit(hunter);进行请求,而service为PicassoExecutorService类的实例化对象,PicassoExecutorService为线程池执行服务,主要用来发进行线程的请求(BitmapHunter),而请求的所有逻辑都在其参数(hunter的run()方法中),因此,我们需要学习一下BitmapHunter类中run()方法的执行逻辑,其方法的源码如下所求:

@Override public void run() {
    try {
      //更新线程的想着信息
      updateThreadName(data);

      if (picasso.loggingEnabled) {
        log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
      }
      //进行Bimtap的获取
      result = hunt();

      if (result == null) {
        dispatcher.dispatchFailed(this);
      } else {
        dispatcher.dispatchComplete(this);
      }
    } catch (Downloader.ResponseException e) {
      if (!e.localCacheOnly || e.responseCode != 504) {
        exception = e;
      }
      dispatcher.dispatchFailed(this);
    } catch (NetworkRequestHandler.ContentLengthException e) {
      exception = e;
      dispatcher.dispatchRetry(this);
    } catch (IOException e) {
      exception = e;
      dispatcher.dispatchRetry(this);
    } catch (OutOfMemoryError e) {
      StringWriter writer = new StringWriter();
      stats.createSnapshot().dump(new PrintWriter(writer));
      exception = new RuntimeException(writer.toString(), e);
      dispatcher.dispatchFailed(this);
    } catch (Exception e) {
      exception = e;
      dispatcher.dispatchFailed(this);
    } finally {
      Thread.currentThread().setName(Utils.THREAD_IDLE_NAME);
    }
  }

在run()方法中通过hunt()来获取Bitmap对象,hunt()方法的源码如下所求:

Bitmap hunt() throws IOException {
    Bitmap bitmap = null;
    //从缓存中获取Bitmap
    if (shouldReadFromMemoryCache(memoryPolicy)) {
      bitmap = cache.get(key);
      if (bitmap != null) {
        stats.dispatchCacheHit();
        loadedFrom = MEMORY;
        if (picasso.loggingEnabled) {
          log(OWNER_HUNTER, VERB_DECODED, data.logId(), "from cache");
        }
        return bitmap;
      }
    }
    //从网络上获取Bitmap
    data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
    RequestHandler.Result result = requestHandler.load(data, networkPolicy);
    if (result != null) {
      loadedFrom = result.getLoadedFrom();
      exifRotation = result.getExifOrientation();

      bitmap = result.getBitmap();

      // If there was no Bitmap then we need to decode it from the stream.
      if (bitmap == null) {
        InputStream is = result.getStream();
        try {
          bitmap = decodeStream(is, data);
        } finally {
          Utils.closeQuietly(is);
        }
      }
    }

    if (bitmap != null) {
      if (picasso.loggingEnabled) {
        log(OWNER_HUNTER, VERB_DECODED, data.logId());
      }
      stats.dispatchBitmapDecoded(bitmap);
      if (data.needsTransformation() || exifRotation != 0) {
        synchronized (DECODE_LOCK) {
          if (data.needsMatrixTransform() || exifRotation != 0) {
            bitmap = transformResult(data, bitmap, exifRotation);
            if (picasso.loggingEnabled) {
              log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId());
            }
          }
          if (data.hasCustomTransformations()) {
            bitmap = applyCustomTransformations(data.transformations, bitmap);
            if (picasso.loggingEnabled) {
              log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId(), "from custom transformations");
            }
          }
        }
        if (bitmap != null) {
          stats.dispatchBitmapTransformed(bitmap);
        }
      }
    }

    return bitmap;
  }

在上面的run()中当获得Bitmap result后,通过分发器调用dispatcher.dispatchComplete(this)方法通过Handler来发送HUNTER_COMPLETE消息执行 performComplete(hunter) 调用batch(hunter)方法来发送 HUNTER_DELAY_NEXT_BATCH 消息并执行dispatcher.performBatchComplete()方法来送 HUNTER_BATCH_COMPLETE 消息到Picasso对象主线程的HANDLER中,在Handler中收到消息的处理逻辑如下:

@SuppressWarnings("unchecked") 
List<BitmapHunter> batch = (List<BitmapHunter>) msg.obj;
    //noinspection ForLoopReplaceableByForEach
          for (int i = 0, n = batch.size(); i < n; i++) {
            BitmapHunter hunter = batch.get(i);
            hunter.picasso.complete(hunter);
          }

然后调用picasso.complete(hunter)方法,源码如下:

void complete(BitmapHunter hunter) {
    Action single = hunter.getAction();
    List<Action> joined = hunter.getActions();

    boolean hasMultiple = joined != null && !joined.isEmpty();
    boolean shouldDeliver = single != null || hasMultiple;

    if (!shouldDeliver) {
      return;
    }

    Uri uri = hunter.getData().uri;
    Exception exception = hunter.getException();
    Bitmap result = hunter.getResult();
    LoadedFrom from = hunter.getLoadedFrom();

    if (single != null) {
      deliverAction(result, from, single);
    }

    if (hasMultiple) {
      //noinspection ForLoopReplaceableByForEach
      for (int i = 0, n = joined.size(); i < n; i++) {
        Action join = joined.get(i);
        deliverAction(result, from, join);
      }
    }

    if (listener != null && exception != null) {
      listener.onImageLoadFailed(this, uri, exception);
    }
  }

从上面代码中可以看到,该方法最后会执行deliverAction(result,from,join/single)来继续执行,方法deliverAction方法的源码如下:

private void deliverAction(Bitmap result, LoadedFrom from, Action action) {
    if (action.isCancelled()) {
      return;
    }
    if (!action.willReplay()) {
      targetToAction.remove(action.getTarget());
    }
    if (result != null) {
      if (from == null) {
        throw new AssertionError("LoadedFrom cannot be null.");
      }
      action.complete(result, from);
      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + from);
      }
    } else {
      action.error();
      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_ERRORED, action.request.logId());
      }
    }
  }

然后会执行 action.complete(result, from);方法,其方法源码如下:

@Override public 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));
    }

    ImageView target = this.target.get();
    if (target == null) {
      return;
    }

    Context context = picasso.context;
    boolean indicatorsEnabled = picasso.indicatorsEnabled;
    PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled);

    if (callback != null) {
      callback.onSuccess();
    }
  }

//上面方法通过PicassoDrawable.setBitmap来给imageview设置图片显示  
/*----------------------------------------*/

static void setBitmap(ImageView target, Context context, Bitmap bitmap,
      Picasso.LoadedFrom loadedFrom, boolean noFade, boolean debugging) {
    Drawable placeholder = target.getDrawable();
    if (placeholder instanceof AnimationDrawable) {
      ((AnimationDrawable) placeholder).stop();
    }
    PicassoDrawable drawable =
        new PicassoDrawable(context, bitmap, placeholder, loadedFrom, noFade, debugging);
    target.setImageDrawable(drawable);
  }

通过调用PicassoDrawable.setBitmap()方法把从网络上请求下来的Bimtap设置到ImageView的控件上,这样一张图片就通过Picasso的加载机制把一个指定的path的图片显示出来了!

Picasso图片加载库的默认缓存大小,最大为50MB,最小为5MB

private static final int MIN_DISK_CACHE_SIZE = 5 * 1024 * 1024; // 5MB
private static final int MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值