图片加载库-Picasso源码分析

我们使用 Picasso 十分的简单,只需调用下面一句就可以使用他了。

Picasso.with(this).load("http://4493bz.1985t.com/uploads/allimg/160513/3-160513102334.jpg")
            .into(mIvNormal);

那么分析也从这里开始入手

Picasso对象的创建

Picasso.java

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

在With方法中,很明显singleton 是 Picasso 的单例对象 , 而这个单例对象是用 Picasso 类中的一个静态内部类 Builder 来实现的。 那么接下来就看看 build 方法里面做了什么吧

public Picasso build() {
  Context context = this.context;
    // 注 1
  if (downloader == null) {
    downloader = Utils.createDefaultDownloader(context);
  }
    // 注 2
  if (cache == null) {
    cache = new LruCache(context);
  }
    // 注 3
  if (service == null) {
    service = new PicassoExecutorService();
  }
    // 注 4
  if (transformer == null) {
    transformer = RequestTransformer.IDENTITY;
  }
    // 注 5
  Stats stats = new Stats(cache);
    // 注 6
  Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);
    // 注 7
  return new Picasso(context, dispatcher, cache, listener, transformer, requestHandlers, stats,
      defaultBitmapConfig, indicatorsEnabled, loggingEnabled);
}

因为我们使用 Picasso 是使用默认的 Build 对象来创建这个单例的 , 所以会默认配置一些所需的对象。

注 1 :downloader 是下载器,使用的是默认,如果网络请求是使用的是 OkHttp 的话,那么就使用 OkHttp 来进来加载图片 ,否则使用 HttpURLConnection 。

注 2 : cache 使用 LruCache 缓存

注 3 : service 使用 PicassoExecutorService , service其实就是 线程池 ,默认的线程数是 3 ,里面实现它的是 PriorityBlockingQueue --- 优先队列

注 4 : transformer 他的作用类似于拦截器,在他提交每个请求之前立即调用的变换器。 这可以用来修改关于请求的任何信息。

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

默认不做任何处理

注 5 : stats 状态控制类。 里面有个 HandlerThread 和一个 Handler 。 内部其实就是 Handler 发送信息 ,statsThread 来处理信息。

注 6 : dispatcher , 分发器,用来分发任务。

注 7 : 最后就是创建 一个 Picasso 了。 除了使用过默认的 Picasso ,我们也可以使用 Build 来自定义自己的 Picasso 。

load 加载 URL

创建了 Picasso 对象 ,那么就会使用 load 来加载 URL 了。

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

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

load 方法 最后创建的是 RequestCreator 对象 --- 请求构建器 ,用于存储改图片的加载任务的一切信息。

RequestCreator(Picasso picasso, Uri uri, int resourceId) {
    if (picasso.shutdown) {
      throw new IllegalStateException(
          "Picasso instance already shut down. Cannot submit new requests.");
    }
    this.picasso = picasso;
    // 创建 Request 对象 ,把配置信息放置在 Request 对象中
    this.data = new Request.Builder(uri, resourceId, picasso.defaultBitmapConfig);
}

在 RequestCreator 对象里 ,保存着 一个 Request 的对象 ,而这个对象就封装了 图片加载的请求信息。 比如上面创建了一个新的 Request 对象 ,并把 uri-请求地址,resourceId-所要展示控件ID,与picasso.defaultBitmapConfig -图片的配置(这些配置我们都可以在创建Picasso 时的 Build 中配置)

Picasso.with(this)
            .load("http://4493bz.1985t.com/uploads/allimg/160513/3-160513102334.jpg")
            .resize(500, 500)
            .centerCrop()
            .into(mIvResize);

在我们使用的时候,会为 RequestCreator 设置其他 , 例如上面调用了 resize 方法和 centerCrop 方法,其实最后就是对 Request 对象设置。

把图片加载到 ImageView

RequestCreator配置好了,既Request 对象的参数都设置好了,现在就到了 into 方法了。

  public void into(ImageView target, Callback callback) {
long started = System.nanoTime();
//线程检查 , 必须在主线程
checkMain();
// 没有 url 时抛出异常
if (target == null) {
  throw new IllegalArgumentException("Target must not be null.");
}
// 没有 ImageView显示图片 时抛出异常
if (!data.hasImage()) {
  picasso.cancelRequest(target);
  if (setPlaceholder) {
    setPlaceholder(target, getPlaceholderDrawable());
  }
  return;
}
//仅有fit()方法会修改该flag为true,但是该方法只能由开发者显式调用,因此下面的代码默认是不会执行的
if (deferred) {
  if (data.hasSize()) {
    throw new IllegalStateException("Fit cannot be used with resize.");
  }
// 获取 ImageView 控件的宽高
  int width = target.getWidth();
  int height = target.getHeight();
//如果 宽或高 有个为 0 ,那么加载 默认图 就返回
  if (width == 0 || height == 0) {
    //设置了默认图就加载
    if (setPlaceholder) {
      setPlaceholder(target, getPlaceholderDrawable());
    }
    //记录
    picasso.defer(target, new DeferredRequestCreator(this, target, callback));
    return;
  }
  data.resize(width, height);
}
// 注 1
Request request = createRequest(started);
String requestKey = createKey(request);
// 注 2
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());
}
// 创建一个 ImageViewAction ,提供给 enqueueAndSubmit 方法
Action action =
    new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
        errorDrawable, requestKey, tag, callback, noFade);

//注 3
picasso.enqueueAndSubmit(action);

}

注 1 : 通过 createRequest 来创建 Request 对象

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

    // 获取 request 的对象
    Request request = data.build();

    ......

    //对 request 对象进行 转变,因为使用默认的,所以并没有改变request对象
    Request transformed = picasso.transformRequest(request);
    if (transformed != request) {
      //判断如果请求已更改,请复制原始ID和时间戳。
      transformed.id = id;
      transformed.started = started;

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

}

因为在 调用 Picasso build 方法的时候,会设置 transformer --- 上文所说的 类似拦截器的 ,会对 request 进行修改并返回一个新的的, 但是因为使用 的是默认的,所以并没有改变 request 对象。

注 2 : 缓存策略,是否应该从内存中读取。如果使用的话,就从内存中快速读取。如果bitmap存在就直接把图片设置给ImageView 。

注 3 : 提交请求,进行网络访问。

void enqueueAndSubmit(Action action) {
Object target = action.getTarget();
if (target != null && targetToAction.get(target) != action) {
  cancelExistingRequest(target);
  targetToAction.put(target, action);
}
submit(action);

}

targetToAction 是一个 map ,key是imageView,value是Action 。提交时做判断,如果targetToAction里面已经有了当前imageView,那么判断当前Action与之前的Action是否相同,如果不相同则取消之前的任务并将新的key-value加入到map 。 最后提交 Action -- 任务

Dispatcher 任务分发器

Dispatcher 会通过Handler来提交任务,然后交由Handler的handleMessage方法来执行,最后就会调用到Dispatcher的 performSubmit 方法。

void performSubmit(Action action, boolean dismissFailed) {
    ......
    
    //注 1
    BitmapHunter hunter = hunterMap.get(action.getKey());
    if (hunter != null) {
      hunter.attach(action);
      return;
    }

    if (service.isShutdown()) {
      ....
      return;
    }

    // 注 2
    hunter = forRequest(action.getPicasso(), this, cache, stats, action);
    // 注 3
    hunter.future = service.submit(hunter);
    // 将 BitmapHunter 缓存在 map 中
    hunterMap.put(action.getKey(), hunter);
    if (dismissFailed) {
      failedActions.remove(action.getTarget());
    }

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

注 1 : 是一个Runnable的子类,用来进行Bitmap的获取(网络,硬盘,内存等) 。查看是否有对应url的缓存的hunter,如果有就把当前 调用 BitmapHunter 的 attach 方法。

注 2 : 创建一个新的 BitmapHunter 对象

static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats,
  Action action) {
    Request request = action.getRequest();
    List requestHandlers = picasso.getRequestHandlers();

    for (int i = 0, count = requestHandlers.size(); i < count; i++) {
      RequestHandler requestHandler = requestHandlers.get(i);
      if (requestHandler.canHandleRequest(request)) {
        return new BitmapHunter(picasso, dispatcher, cache, stats, action, requestHandler);
      }
    }

    return new BitmapHunter(picasso, dispatcher, cache, stats, action, ERRORING_HANDLER);
}

picasso.getRequestHandlers();是获取请求处理的方式。requestHandlers里面默认保存了一个集合,里面存储了每一类图片的加载。这个集合是在 Picasso 的构造函数里面添加的。有处理Asset、File、Network等...

Picasso( 参数 .....) {
.....
List allRequestHandlers =
    new ArrayList(builtInHandlers + extraCount);

allRequestHandlers.add(new ResourceRequestHandler(context));
if (extraRequestHandlers != null) {
  allRequestHandlers.addAll(extraRequestHandlers);
}
allRequestHandlers.add(new ContactsPhotoRequestHandler(context));
allRequestHandlers.add(new MediaStoreRequestHandler(context));
allRequestHandlers.add(new ContentStreamRequestHandler(context));
allRequestHandlers.add(new AssetRequestHandler(context));
allRequestHandlers.add(new FileRequestHandler(context));
allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats));
requestHandlers = Collections.unmodifiableList(allRequestHandlers);
.....

}

注 3 : 把 BitmapHunter 提交任务到线程池
因为 BitmapHunter 实现了 Runnable ,那么在线程池中就会被调用 run 方法。

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

      ....
      // 注 1 
      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) {
        // 处理 OOM 
      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);
    }
}

注 1 : hunt 方法 就是对bitmap的获取,从内存、硬盘、网络获取。

Bitmap hunt() throws IOException {
    Bitmap bitmap = null;
    // 是否从内存获取
    if (shouldReadFromMemoryCache(memoryPolicy)) {
      bitmap = cache.get(key);
      if (bitmap != null) {
        //发送一个内存缓存中查找成功的消息
        stats.dispatchCacheHit();
        loadedFrom = MEMORY;
        ...
        return bitmap;
      }
    }
    
    //NO_CACHE:跳过检查硬盘缓存,强制从网络获取
    //NO_STORE:不存储到本地硬盘
    //OFFLINE:只从本地硬盘获取,不走网络
    // 注 1 
    data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
    // 注 2
    RequestHandler.Result result = requestHandler.load(data, networkPolicy);
    if (result != null) {
      //获取加载途径(硬盘,内存,网络) 
      loadedFrom = result.getLoadedFrom();
      exifRotation = result.getExifOrientation();

      bitmap = result.getBitmap();

      // 返回的resuslt中包括了bitmap和inputstream,如果bitmap为null则需要自己从stream中读取
      if (bitmap == null) {
        InputStream is = result.getStream();
        try {
          bitmap = decodeStream(is, data);
        } finally {
          Utils.closeQuietly(is);
        }
      }
    }

    if (bitmap != null) {
      ....
    //修改stats中记录的图片的个数(originalBitmapCount)和占用的内存总大小(totalOriginalBitmapSize)以及平均内存占用量(averageOriginalBitmapSize)
      stats.dispatchBitmapDecoded(bitmap);
      if (data.needsTransformation() || exifRotation != 0) {
        synchronized (DECODE_LOCK) {
        //图片是否需要旋转或者其他操作处理
          if (data.needsMatrixTransform() || exifRotation != 0) {
            bitmap = transformResult(data, bitmap, exifRotation);
            ....
          }
        //自定义的图片处理。 这个设置是在 RequestCreator 类中 ,通过 transform 方法为他设置。
          if (data.hasCustomTransformations()) {
            //在里面会读取 transformations ,对结果进行转换
            bitmap = applyCustomTransformations(data.transformations, bitmap);
            ...
          }
        }
        // 记录下图片处理的次数(transformedBitmapCount)以及处理后的占用的总内存大小(totalTransformedBitmapSize)以及每张图片的平均内存占用量(averageTransformedBitmapSize)
        if (bitmap != null) {
          stats.dispatchBitmapTransformed(bitmap);
        }
      }
    }
    
    return bitmap;
}

注 1 :

this.retryCount = requestHandler.getRetryCount();

在 RequestHandler.java 里

int getRetryCount() {
    return 0;
}

从各个 RequestHandler 这个抽象类看的出返回的是零,而 NetworkRequestHandler -- 从网络加载 ,则重写了这个方法 ,返回不再是 0

static final int RETRY_COUNT = 2;
@Override int getRetryCount() {
    return RETRY_COUNT;
}

判断 retryCount 是否为 0 ,如果为 0 ,则走本地读取,否则认为这个是网络加载。

注 2 : 那么加载图片的逻辑全部放在了 requestHandler 里的 load 里面了。

根据不同的 requestHandler 子类来实现不同来源图片的加载。

读取 硬盘文件 , 那么使用的就是 FileRequestHandler

@Override public Result load(Request request, int networkPolicy) throws IOException {
    return new Result(null, getInputStream(request), DISK, getFileExifRotation(request.uri));
}

getInputStream 方法 就是对本地文件的读取。

读取 网络图片 , 使用就是 NetworkRequestHandler

@Override public Result load(Request request, int networkPolicy) throws IOException {
    // 注 1
    Response response = downloader.load(request.uri, request.networkPolicy);
    if (response == null) {
      return null;
    }
    // 判断从 哪里加载的 (缓存还是网络)
    Picasso.LoadedFrom loadedFrom = response.cached ? DISK : NETWORK;

    Bitmap bitmap = response.getBitmap();
    if (bitmap != null) {
      return new Result(bitmap, loadedFrom);
    }

    InputStream is = response.getInputStream();
    if (is == null) {
      return null;
    }
    //本地读取
    if (loadedFrom == DISK && response.getContentLength() == 0) {
      Utils.closeQuietly(is);
      throw new ContentLengthException("Received response with 0 content-length header.");
    }
    //网络读取
    if (loadedFrom == NETWORK && response.getContentLength() > 0) {
    // 记录下图片网络下载的次数(downloadCount)以及总共下载的大小(totalDownloadSize)以及每张图片的平均下载的大小(averageDownloadSize)
      stats.dispatchDownloadFinished(response.getContentLength());
    }
    return new Result(is, loadedFrom);
}

注 1 : 因为 downloader 是一个接口 实现他的有两个类 (UrlConnectionDownloader 、 OkHttpDownloader),如果 OKhttp 可以使用 , 那么downloader 就是 OkHttpDownloader

下面以 OkHttpDownloader 来看

OkHttpDownloader.java

@Override public Response load(Uri uri, int networkPolicy) throws IOException {
    CacheControl cacheControl = null;
    if (networkPolicy != 0) {
        //只走本地缓存
      if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
        cacheControl = CacheControl.FORCE_CACHE;
      } else {
        //自定义缓存策略
        CacheControl.Builder builder = new CacheControl.Builder();
        if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {    
        //不从硬盘读
          builder.noCache();
        }
        if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
        //不写入硬盘
          builder.noStore();
        }
        cacheControl = builder.build();
      }
    }
    
    Request.Builder builder = new Request.Builder().url(uri.toString());
    if (cacheControl != null) {
      builder.cacheControl(cacheControl);
    }
    // 最后就调用了 OKhttp 请求来进行网络访问了。 其网络的加载,网络的缓存全部交给了 Okhttp 来做。
    com.squareup.okhttp.Response response = client.newCall(builder.build()).execute();
    .....
    
    boolean fromCache = response.cacheResponse() != null;
    
    ResponseBody responseBody = response.body();
    return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength());
}

现在就回到 BitmapHunter 里面的 run 方法吧,获得了 bitmap 后,会根据是否加载成功调用相对应的方法。

  1. dispatchComplete 成功
  2. dispatchFailed 失败
  3. dispatchRetry 重试

那么就看看处理bitmap成功获取后的逻辑

Dispatcher.java

发送信息

void dispatchComplete(BitmapHunter hunter) {
    handler.sendMessage(handler.obtainMessage(HUNTER_COMPLETE, hunter));
}

处理信息

void performComplete(BitmapHunter hunter) {
    //是否能写入内存,如果能就写入
    if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
      cache.set(hunter.getKey(), hunter.getResult());
    }
    // hunterMap 处理完就移除
    hunterMap.remove(hunter.getKey());
    //再次发送信息,最后执行 performBatchComplete 方法
    batch(hunter);
    ....
}

void performBatchComplete() {
    List copy = new ArrayList(batch);
    batch.clear();
    // mainThreadHandler 发送信息。
    mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));
    logBatch(copy);
}

而这个 mainThreadHandler 就要回调 , Picasso 类的 build方法里面

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

HANDLER 就是 mainThreadHandler 。那么就看看 HANDLER 做了什么。

static final Handler HANDLER = new Handler(Looper.getMainLooper()) {
@Override public void handleMessage(Message msg) {
    switch (msg.what) {
    case HUNTER_BATCH_COMPLETE: {
      @SuppressWarnings("unchecked") List batch = (List) msg.obj;
      //noinspection ForLoopReplaceableByForEach
      for (int i = 0, n = batch.size(); i < n; i++) {
        BitmapHunter hunter = batch.get(i);
        hunter.picasso.complete(hunter);
      }
      break;
    }
    .....
};

最后就会 回调 complete 方法

void complete(BitmapHunter hunter) {
    Action single = hunter.getAction();
    List 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();
    // 单个 Action
    if (single != null) {
      deliverAction(result, from, single);
    }
    // 有多个 Action
    if (hasMultiple) {
      //noinspection ForLoopReplaceableByForEach
      for (int i = 0, n = joined.size(); i < n; i++) {
        Action join = joined.get(i);
        deliverAction(result, from, join);
      }
    }
    // listener 回调 ,因为没有设置 ,默认 为 null
    if (listener != null && exception != null) {
      listener.onImageLoadFailed(this, uri, exception);
    }
}

那么接下来就是执行 deliverAction 方法了 。 hunter.getAction(); 所获取的Action其实就是 在 RequestCreator 类中 的 into 方法 中 设置的 ImageViewAction 。

private void deliverAction(Bitmap result, LoadedFrom from, Action action) {
    .....
      action.complete(result, from);
    .....
}

那么调用的就是 ImageViewAction 的 complete 方法。

ImageViewAction.java

@Override public void complete(Bitmap result, Picasso.LoadedFrom from) {
    if (result == null) {

    ....
    
    Context context = picasso.context;
    //是否展示来源的标签,默认不展示。
    boolean indicatorsEnabled = picasso.indicatorsEnabled;
    //注 1
    PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled);
    // callback 不为空 就直接回调 callback 的 onSuccess 方法
    if (callback != null) {
    callback.onSuccess();
    }
}

注 1 :

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

最终扔到ImageView上现实的的是PicassoDrawable. 最后图片就加载了。

你可能感兴趣的:(图片加载库-Picasso源码分析)