美文网首页
Android_图片加载库

Android_图片加载库

作者: 738bc070cd74 | 来源:发表于2015-11-30 10:10 被阅读178次
    1. 请求分发模块。负责封装请求,对请求进行优先级排序,并按照类型进行分发。
    2. 缓存模块。通常包括一个二级的缓存,内存缓存、磁盘缓存。并预置多种缓存策略。
    3. 下载模块。负责下载网络图片。
    4. 监控模块。负责监控缓存命中率、内存占用、加载图片平均耗时等。
    5. 图片处理模块。负责对图片进行压缩、变换等处理。
    6. 本地资源加载模块。负责加载本地资源,如assert、drawable、sdcard等。
      7.显示模块。负责将图片输出显示。
    图片加载库

    Picasso 使用

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

    Picasso.with()

    Picasso 的入口函数,用于创建全局唯一的Picasso 实例,使用 double-check 单例模式

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

    with方法内部通过Builder模式创建Picasso 实例

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

    使用默认的缓存策略,内存缓存基于LruCache,磁盘缓存基于http缓存,HttpResponseCache
    创建默认的下载器
    创建默认的线程池(3个worker线程)
    创建默认的Transformer,这个Transformer什么事情也不干,只负责转发请求
    创建默认的监控器(Stats),用于统计缓存命中率、下载时长等等
    创建默认的处理器集合,即RequestHandlers.它们分别会处理不同的加载请求

    load(url)

    多种重载方法,load()方法用于从不同地方加载图片,比如网络、resource、File等,只是创建了一个RequestCreator

    public RequestCreator load(...) {
    
        return new RequestCreator(...);
    }
    

    RequestCreator

    RequestCreator是一个封装请求的类,请求在Picasso中被抽象成Request。RequestCreator类提供了 诸如placeholder、tag、error、memoryPolicy、networkPolicy等方法.
    Request也使用了Builder模式:

    RequestCreator(Picasso picasso, Uri uri, int resourceId)
    

    RequestCreator.into()

    into方法有多种重载,Picasso不仅仅可以 将图片加载到ImageView上,还可以加载Target或者RemoteView上.

    public void into(Target target) {
    long started = System.nanoTime();
    //检查是否在主线程运行
    checkMain();
    
    if (target == null) {
      throw new IllegalArgumentException("Target must not be null.");
    }
    if (deferred) {
      throw new IllegalStateException("Fit cannot be used with a Target.");
    }
    
    if (!data.hasImage()) {
      picasso.cancelRequest(target);
      target.onPrepareLoad(setPlaceholder ? getPlaceholderDrawable() : null);
      return;
    }
    //创建request
    Request request = createRequest(started);
    String requestKey = createKey(request);
    
    if (shouldReadFromMemoryCache(memoryPolicy)) {//是否需要在缓存里面先查找
      Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);//使用请求生成的key查找缓存
      if (bitmap != null) {
        picasso.cancelRequest(target);
        target.onBitmapLoaded(bitmap, MEMORY);
        return;
      }
    }
    
    target.onPrepareLoad(setPlaceholder ? getPlaceholderDrawable() : null);
    
    // 将request封装成action
    Action action =
        new TargetAction(picasso, target, request, memoryPolicy, networkPolicy, errorDrawable,
            requestKey, tag, errorResId);
    // 提交action
    picasso.enqueueAndSubmit(action);
    }
    

    Request
    关注的是请求本身,比如请求的源、id、开始时间、图片变换配置、优先级等等,而Action则代表的是一个加载任务,所以不仅需要 Request对象的引用,还需要Picasso实例,是否重试加载等等
    Action
    有个需要关注的点,那就是WeakReference<T> target,它持有的是Target(比如ImageView..)的弱引用,这样可以保证加载时间很长的情况下 也不会影响到Target的回收了.

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

    enqueueAndSubmit 它会先从action任务上拿到对应target,也就是imageView,然后从weakHashMap中通过这个imageView索引到对应的action,如果 发现这个action跟传进来的action不一样的话,那就取消掉之前的加载任务。最后将当前加载任务提交.

    最终调用的是Dispatcher的dispatchSubmit(action)方法.
    Dispatcher即任务分发器,它是在 Picasso实例创建的时候初始化的.。

    Dispatcher

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

    每一个Dispatcher都需要关联线程池(service)、下载器(downloader)、主线程的Handler(HANDLER)、缓存(cache)、 监控器(stats).

    PicassoExecutorService

    private static final int DEFAULT_THREAD_COUNT = 3;
    
    PicassoExecutorService() {
    super(DEFAULT_THREAD_COUNT, DEFAULT_THREAD_COUNT, 0, TimeUnit.MILLISECONDS,
        new PriorityBlockingQueue<Runnable>(), new Utils.PicassoThreadFactory());
    }
    

    默认线程数量为 3.但是PicassoExecutorService的特性是可以根据网络情况调整线程数量,wifi下是4个线程,而2g网只有一个线程。具体是 通过在Dispatcher中注册了监听网络变化的广播接收者。

    DispatcherThread 是 Dispatcher 的内部类

    static class DispatcherThread extends HandlerThread
    

    切换到子线程

    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实现Runnable接口,可以被线程池调用。然后判断线程池有没有关闭,如果没有的话, 就会将这个bitmapHunter submit线程池里面

    forRequest

    static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats,
      Action action) {
    Request request = action.getRequest();
    List<RequestHandler> requestHandlers = picasso.getRequestHandlers();
    
    // Index-based loop to avoid allocating an iterator.
    //noinspection ForLoopReplaceableByForEach
    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 构造器添加的requestHnadlers创建 BitmapHunter
    BitmapHunter的run 方法会调用 hunt方法,hunt方法先从缓存拿,缓存没有命中的话,再调用requestHandler.load.
    hunt 方法最终会返回一个bitmap,在run方法中处理

      result = hunt();
    
      if (result == null) {
        dispatcher.dispatchFailed(this);
      } else {
        dispatcher.dispatchComplete(this);
      }
    

    dispatcher 使用内部子线程handler处理

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

    handler调用performComplete

    case HUNTER_COMPLETE: {
          BitmapHunter hunter = (BitmapHunter) msg.obj;
          dispatcher.performComplete(hunter);
          break;
        }
    

    会根据事先设置的缓存策略决定是否将结果加到内存缓存。然后调用batch方法

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

    这个方法会把结果暂存, 然后批量处理(等待200ms),这样做也是为了防止短时间大量任务阻塞消息队列。到时间后,就会执行performBatchComplete
    , 此方法会将这个批次的所有结果一次性发给主线程的Handler

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

    在Picasso初始化的时候创建了一个主线程handler,

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

    主线程接到消息。调用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);
    }
    }
    

    complete方法会调用deliverAction方法,最终其实调用的是具体 action的complete方法,如果是ImageView的话,那就是ImageViewAction的complete方法

    NetworkRequestHandler

    @Override public Result load(Request request, int networkPolicy) throws IOException {
    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;
    }
    // Sometimes response content length is zero when requests are being replayed. Haven't found
    // root cause to this but retrying the request seems safe to do so.
    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) {
      stats.dispatchDownloadFinished(response.getContentLength());
    }
    return new Result(is, loadedFrom);
    }
    

    这里会创建一个 downloader

    static Downloader createDefaultDownloader(Context context) {
    if (SDK_INT >= GINGERBREAD) {
        try {
          Class.forName("com.squareup.okhttp.OkHttpClient");
          return OkHttpLoaderCreator.create(context);
        } catch (ClassNotFoundException ignored) {
        }
    }
    return new UrlConnectionDownloader(context);
    }
    

    picasso http://blog.csdn.net/chdjj/article/details/49964901

    相关文章

      网友评论

          本文标题:Android_图片加载库

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