简单说说我最经常使用的图片加载库 Picasso

对于一个须要展现不少图片或较多图片的App来讲,一个好的图片加载框架是必不可少的。在我刚开始学习Android的时候,什么都想本身写,我之前作过一个看漫画的App,里面的图片加载,缓存等都是本身写的,可是效果并不理想,当时利用了LruCache来作图片的内存缓存,用DiskLruCache作磁盘缓存,加载图片根据Key先在内存中查询,若是没有就再去磁盘中查询,若果再没有在去网络上加载。虽然是个逻辑上很是清楚的事,可是要真的作好仍是有必定的难度的。后来我认识到了Picasso,一个优雅、强大的图片加载框架,我使用它制做了许多的项目。虽然Picasso不是最强大的,如今有GlideFresco这些更强大的图片加载库,但在我眼里Picasso绝对是最优雅的,从它的API,设计方法,源码看,Picasso集轻量、实用于一身。java

第一眼

认识它的第一眼确定是它超级简短的使用方法,只须要一行代码,链式配置咱们要加载的图片和一些加载配置和指定的加载Target,咱们的图片就正确的加载并显示在了界面上,不可谓不优雅。设计模式

Picasso.with(context).load(url).into(imageView);复制代码

咱们还能够很方便的配置各类加载选项,好比设置占位图,设置错误图,设置是否须要对图片进行变换,图片显示是否须要淡入效果,对图片的大小进行调整等经常使用的配置,这些都只须要一行代码就能够解决。缓存

那么它是怎么作到的呢?做为一个开发者,首先要学会使用一个库,在学会了使用后,咱们要去了解它,了解它的设计,了解它的实现,从中学习优秀的设计思想和编码技巧。网络

掌握一切的男人——Picasso(毕加索)

从使用上看,Picasso类无疑是掌握着一切的类,做为一个全局单例类,它掌握着各类配置(内存、磁盘、BitmapConfig、线程池等),提供各类简单有用的方法并隐藏了内部的各类实现,是咱们使用上的超级核心类。Picasso的构造方法提供包级别的访问权限,咱们不能直接new出来,但咱们能够很简单的经过app

Picasso.with(context)复制代码

来获取这个全局单例对象,来看一下with()方法框架

public static Picasso with(@NonNull Context context) {
    if (context == null) {
      throw new IllegalArgumentException("context == null");
    }
    if (singleton == null) {
      synchronized (Picasso.class) {
        if (singleton == null) {
          singleton = new Builder(context).build();
        }
      }
    }
    return singleton;
  }复制代码

一个很经典的单例实现,内部使用建造者模式对Picasso对象进行构造。对于大多数简单的应用,只须要使用默认的配置就行了。可是对于一些应用,咱们也能够经过Picasso.Builder来进行自定义的配置。咱们能够根据相似下面的代码进行Picasso的配置ide

Picasso picasso = new Picasso.Builder(this)
        .loggingEnabled(true)
        .defaultBitmapConfig(Bitmap.Config.RGB_565)
        .build();
Picasso.setSingletonInstance(picasso);复制代码

因为Picasso是一个很是复杂的对象,根据不一样的配置会产生不一样的表现,这里经过建造者模式来构建对象很好的将构建和其表现分离。oop

RequestCreator

经过Picasso对象,咱们能够load各类图片资源,这个资源能够字符路径、Uri、资源路径,文件等形式提供,以后Picasso会发挥一个RequestCreator对象,它能够根据咱们需求以及图片资源生成相应的Request对象。以后Request会生成Action*对象,以后会分析这一系列的过程。因为RequestCreator的配置方法都返回自身,因而咱们能够很方便的链式调用。源码分析

RequestCreator requestCreator = Picasso.with(this)
        .load("http://image.com")
        .config(Bitmap.Config.RGB_565)
        .centerInside()
        .fit()
        .memoryPolicy(MemoryPolicy.NO_CACHE)
        .noPlaceholder()
        .noFade();复制代码

into target——谈加载过程

requestCreator.into(new ImageView(this));复制代码

生成了RequestCreator后,咱们能够调用其into()方法,该方法接受能够接收一个ImageView或者RemoteView或者Target对象,固然最后他们都会变为相应的Target对象来进行内部的图片加载。学习

接下来咱们就来分析一下这被隐藏起来的加载过程。这里以最经常使用的into(imageView)进行分析。

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;
  }

  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);
  }

  Request request = createRequest(started);
  String requestKey = createKey(request);

  if (shouldReadFromMemoryCache(memoryPolicy)) {
    Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
    if (bitmap != null) {
      picasso.cancelRequest(target);
      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);
}复制代码

这个方法有点长,咱们一点一点看,首先它检查了当前是否为主线程,若为主线程就抛出异常。

static void checkMain() {
  if (!isMain()) {
    throw new IllegalStateException("Method call should happen from the main thread.");
  }
}复制代码

以后判断咱们给的图片的资源路径是否合法,若是不合法会取消生成请求,并直接显示占位图

if (!data.hasImage()) {
  picasso.cancelRequest(target);
  if (setPlaceholder) {
    setPlaceholder(target, getPlaceholderDrawable());
  }
  return;
}复制代码

若给的图片资源路径不为空,会检查一个defer字段的真假,只有当咱们设置fit()时,defer才为true,由于fit()方法会让加载的图片以适应咱们ImageView,因此只有当咱们的ImageView laid out后才会去进行图片的获取并剪裁以适应。这里就不具体分析了,接下来往下看。

Request request = createRequest(started);

private Request createRequest(long started) {
    int id = nextId.getAndIncrement();

    Request request = data.build();
    request.id = id;
    request.started = started;

    boolean loggingEnabled = picasso.loggingEnabled;
    if (loggingEnabled) {
      log(OWNER_MAIN, VERB_CREATED, request.plainId(), request.toString());
    }

    Request transformed = picasso.transformRequest(request);
    if (transformed != request) {
      // If the request was changed, copy over the id and timestamp from the original.
      transformed.id = id;
      transformed.started = started;

      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_CHANGED, transformed.logId(), "into " + transformed);
      }
    }

    return transformed;
  }复制代码

接下来,终于生成了咱们的Request对象,同Http请求的Request对象相同,这个Request对象包含了许多咱们须要的信息已得到准确的回应。这里注意,咱们的Request对象是能够经过RequestTransformer通过变换的,默认Picasso中内置的是一个什么也不变的RequestTransformer

默认的RequestTransformer

RequestTransformer IDENTITY = new RequestTransformer() {
  @Override public Request transformRequest(Request request) {
    return request;
  }
};复制代码

生成了Request对象后,这里来到了咱们熟悉的一个步骤,就是检查内存中是否已经有图片的缓存了,固然它还更具咱们设置的内存策略进行了是否须要进行内存检查。好比咱们在查看大图的时候,通常会选择不让大图在内存缓存中存在,而是每次都去请求。

if (shouldReadFromMemoryCache(memoryPolicy)) {
      Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
      if (bitmap != null) {
        picasso.cancelRequest(target);
        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;
      }
    }复制代码

找到的话就取消请求。不然会更具是否须要设置占位设置一下展位图,而后生成一个Action对象并使其加入队列发出。

if (setPlaceholder) {
  setPlaceholder(target, getPlaceholderDrawable());
}

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

picasso.enqueueAndSubmit(action);复制代码

这个Action对象包含了咱们的目标Target和请求数据Request以及相应的回调Callback等信息。

到这里咱们仍是没有真正的进行加载,最多只在内存中进行了缓存查询。

Go Action

经过上面的代码调用,咱们了解到Picasso发出了一个Action,就像一个导演同样,说Action的时候就开始拍戏了,咱们的Picasso在发出Action后就开始正式加载图片了。

Action最终会被Dispatcher给分发出去。

void submit(Action action) {
  dispatcher.dispatchSubmit(action);
}复制代码

Dispatcher随着Picasso的初始化而生成,正如其名,它负责全部Action的分发并将收到的结果也进行分发,分发给Picasso对象。咱们来分析一下Dispatcher的工做过程。

Dispatcher内部是经过Handler进行工做的,这里插下嘴,Handler真是Android中超级强大的类,帮助咱们轻松的实现线程之间的通讯、切换,有许多有名的开源库都利用了Handler来实现功能,好比Google自家的响应式框架Agera,内部真是经过Handler实现的。因此咱们要好好的掌握这个强大的类。

很少说了,咱们继续看代码

void dispatchSubmit(Action action) {
  handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
}复制代码

Dispatcher经过内部的Handler发送了一个消息,并将Action对象传递了出去,那么咱们就要找到这个Handler对象的具体实现,根据收到的消息类型它作了哪些事情。

private static class DispatcherHandler extends Handler {
  private final Dispatcher dispatcher;

  public DispatcherHandler(Looper looper, Dispatcher dispatcher) {
    super(looper);
    this.dispatcher = dispatcher;
  }

  @Override public void handleMessage(final Message msg) {
    switch (msg.what) {
      case REQUEST_SUBMIT: {
        Action action = (Action) msg.obj;
        dispatcher.performSubmit(action);
        break;
      }
        ……
    }
  }
}复制代码

很容易找到了,就是执行了performSubmit(action)方法,继续来看下去,这里尚未具体的加载动做。

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;
  }

  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;
  }

  hunter = forRequest(action.getPicasso(), this, cache, stats, action);
  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());
  }
}复制代码

又是一段比较长的代码,可是仍是很容易看懂的。主要就是生成了BitmapHunter对象,并将其发出。

hunter = forRequest(action.getPicasso(), this, cache, stats, action);
hunter.future = service.submit(hunter);复制代码

经过查看代码,咱们知道这个service对象是一个ExecutorService,也就咱们经常使用的线程池,这里Picasso默认使用的是PicassoExecutorService,在Dispatcher内部有一个监听网络变化广播的Receiver,Picasso会根据咱们不一样的网络变化(Wifi,4G,3G,2G)智能的切换线程池中该线程的数量,以帮助咱们更好的节省流量。

既然线程池将BitmapHunter对象发出了,说明这个BitmapHunter对象必定是Runable的子类,从名字上来分析,咱们也能够知道它确定承担了Bitmap的获取生成。点进去一看源码,果真是这样的。哈哈。

线程池submit了一个Runable对象后,必定会调用其run()方法,咱们就来看看它是否是加载了Bitmap吧~

@Override public void run() {
  try {
    updateThreadName(data);

    if (picasso.loggingEnabled) {
      log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
    }

    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);
  }
}复制代码

代码虽长,核心只有hunt()一句,捕猎开始!BitmapHunter这个猎人开始狩猎Bitmap了。

Bitmap hunt() throws IOException {
  Bitmap bitmap = null;

  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;
    }
  }

  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;
}复制代码

这个方法很长,最终返回咱们所指望的Bitmap对象,说明这一个方法正是真正从各个渠道获取Bitmap对象的方法。咱们看到,这里又进行了一次内存缓存的检查,避免两次请求相同图片的重复加载,没有的话,利用RequestHandler对象进行加载。RequestHandler是一个抽象类,load()方法抽象,由于根据不一样图片的加载要执行不一样的操做,好比从网络中获取,从resource中获取,从联系人中获取,从MediaStore获取等,这里运用了模板方法的模式,将一些方法将逻辑相同的方法公用,具体的加载细节子类决定,最终都返回Result对象。

根据不一样的RequestHandler实例,咱们可能能够直接获取一个Bitmap对象,也可能只获取一段流InputStream,好比网络加载图片时。若是结果以流的形式提供,那么Picasso会自动帮咱们将流解析成Bitmap对象。以后根据咱们以前经过RequestCreatorRequest的配置,决定是否对Bitmap对象进行变换,具体实现都大同小异,利用强大的Matrix,最后返回Bitmap。

以后咱们再回到run()方法,假设这里咱们成功获取到了Bitmap,那么是怎么传递的呢?这里仍是利用了Dispatcher

if (result == null) {
  dispatcher.dispatchFailed(this);
} else {
  dispatcher.dispatchComplete(this);
}复制代码

和以前同样,Dispatcher内部经过Handler发送了一个特定的消息,而后执行。

void performComplete(BitmapHunter hunter) {
  if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
    cache.set(hunter.getKey(), hunter.getResult());
  }
  hunterMap.remove(hunter.getKey());
  batch(hunter);
  if (hunter.getPicasso().loggingEnabled) {
    log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for completion");
  }
}复制代码

上面就是它具体作的事,这里着重看batch()方法,相信这个方法必定是经过某种方式将猎人狩猎的Bitmap给上交给国家了。

private void batch(BitmapHunter hunter) {
  if (hunter.isCancelled()) {
    return;
  }
  batch.add(hunter);
  if (!handler.hasMessages(HUNTER_DELAY_NEXT_BATCH)) {
    handler.sendEmptyMessageDelayed(HUNTER_DELAY_NEXT_BATCH, BATCH_DELAY);
  }
}复制代码

咦?这里仍是没有将Bitmap发出,可是经过handler发出了一个消息,恩恩,这都是套路了。这里有个设计很棒的地方,这里发送消息用了延时,为何呢?为何不立刻发送呢?Picasso是将图片一批批的送出去的,每次发送的间隔为200ms,间隔不长也不短,这样有什么好处呢,好处就是若是咱们看到一部分图片是一块儿加载出来的,而不是一张一张加载出来的。这个设计好贴心。前面根据网络状况决定线程池大小的作法也好贴心,Jake大大真是超棒!

找到了这个消息收到后具体执行的方法了

void performBatchComplete() {
  List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);
  batch.clear();
  mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));
  logBatch(copy);
}复制代码

这里就体现了Handler线程通讯与切换的强大之处了,这里经过将一批Bitmap对象交给了处理主线程消息的Handler处理,这样咱们获取到Bitmap并加载到ImageView上就是在主线程了操做的了,咱们去看看这个Handler作了什么。这个Handler是在Dispatcher构造时传进来的,在Picasso类中定义。哈哈,正不亏是掌握一切权与利的对象,最苦最累的活让别人去作,本身作最风光体面的事。

static final Handler HANDLER = new Handler(Looper.getMainLooper()) {
  @Override public void handleMessage(Message msg) {
    switch (msg.what) {
      case HUNTER_BATCH_COMPLETE: {
        @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);
        }
        break;
      }
        ……
    }
};复制代码

很少说了,咱们来看看代码,恩,很清楚的针对每一个BitmapHunter执行了complete()方法,那就去看看喽。

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);
  }
}复制代码

这个方法从BitmapHunter中获取Action对象,若这个Action成功完成,会执行Action的complete()方法,并将结果传入,很明显这是一个回调方法。Action也是一个抽象类,根据咱们的Target不一样会生成不一样的Action对象,好比into(target)方法会生成TargetAction对象,into(imageView)会生成ImageViewAction对象,调用fetch()方法会产生FetchAction对象。这里因为咱们是以将图片加载到ImageView中来分析的,因此咱们只分析一下ImageViewAction的代码。

每一个Action的子类要实现两个回调方法,一个error(),在图片加载失败时触发,一个complete(),在图片成功加载时调用。

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

@Override public void error() {
  ImageView target = this.target.get();
  if (target == null) {
    return;
  }
  Drawable placeholder = target.getDrawable();
  if (placeholder instanceof AnimationDrawable) {
    ((AnimationDrawable) placeholder).stop();
  }
  if (errorResId != 0) {
    target.setImageResource(errorResId);
  } else if (errorDrawable != null) {
    target.setImageDrawable(errorDrawable);
  }

  if (callback != null) {
    callback.onError();
  }
}复制代码

恩,很清楚的看到成功时就正确显示图片,失败时则根据是否设置了错误图来选择是否加载错误图。这里用到了一个PicassoDrawable的类,这个类继承自BitmapDrawable类,经过它,能够很方便的实现淡入淡出效果。

总结

到这里,咱们分析完了一次成功的Picasso图片加载过程,固然咱们不可能每次都成功,也会发生各类错误,或者咱们暂停了加载又继续加载等,这些Picasso都做出了不一样的处理,线程之间经过Handler进行通讯。这里就不一一详述了。相信你们本身会去看的。

不得不说,Picasso真是一个优雅的图片加载库,用极少的代码完成了了不得的事,从API的设计到代码的编写,无不体现了做者的深思熟虑和贴心,运用多用设计模式巧妙地提供极其简单的调用接口,隐藏背后复杂的实现。经过对Picasso的使用与源码分析,我学到了不少,但愿我之后也能够设计出这么优雅实用的库或框架。

天道酬勤,我要加油!

相关文章
相关标签/搜索