Picasso 解析 (1)- 一张图片是如何加载出来的

1,542 阅读6分钟

前言

Picasso是JakeWharton大神在github上的一个开源图片加载框架,使用起来极其方便,甚至只需要一行代码就可以搞定图片加载:

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

具体如何使用该框架我就不在这里赘述了,大家可以自行上官网进行学习。本文主要是针对Picasso中如何通过上面的一句代码将一张网络图片加载出来的流程进行梳理分析。

Picasso.with(context)

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

这是一个典型的双重检查锁定的懒汉式单例模式和建造者模式,我们先来看看单例模式的好处:

(1)使用延迟初始化方式加载对象,保证只有在使用的时候才加载对象。
(2)使用同步代码块来保证就算在多个线程同时调用此方法时,也只会有唯一的单例对象存在。
(3)通过对singleton是否为null的双重检查,保证了代码的效率。

上述两点优势在我们使用RecyclerView、ListView、GridView这样的控件时尤其重要,因为我们可能会有多个view同时用这一段代码来加载图片,这样可以充分保证对象的安全性和加载的效率。

在初始化singleton对象时,采用了建造者模式的方式:

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

因为我们在创建Picsasso对象时,没有指定特别的downloader、cache、service和transormer,所以就全部采用了Picasso为我们提供的默认对象。实际上,我们可以在进行构建的时候,用以下方式自定义这些对象参数:

new Picasso.Builder(this).memoryCache(new LruCache(this)).build().load("http://i.imgur.com/DvpvklR.png").into(image);

当然,这里违反了单例模式,如果我们真的需要自己来指定线程池、下载器这些对象,就需要我们自己维护Picasso的单例对象来进行自定义构建。如果后面有这样的需求,我会单独再写一篇文章来对这种方式进行分析。

load(“i.imgur.com/DvpvklR.png“)

public RequestCreator load(@Nullable 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(@Nullable Uri uri) {
  return new RequestCreator(this, uri, 0);
}

通过我们指定的path,返回了一个RequestCreator对象,这里要提的是,当我们返回的一个对象为null的时候,Picasso对象会为我们创建一个uri为null,resourceId为0的RequestCreator。而如果我们传进来的字符串为空,则会抛出异常,这里针对path为null或者为空的情况做了两种不同的处理。其实我并没有想明白为什么要对这两种情况分别做不同处理,如果有人知道请告诉我。一切正常的话,我们会得到一个由path初始化的uri的RequestCreator对象。

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 || target.isLayoutRequested()) {
                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);
    }

该方法主要是用来创建ImageViewAction对象,并提交由Picasso来进行处理。当然,如果缓存的话,就不用创建该对象,直接就可以显示出来了。总的来说,我们可以总结为下图所示:

Created with Raphaël 2.1.0获取当前时间是否在主线程检查uri或reouceId是否有数据是否设置了fit对data进行resize操作创建request对象和requestKey是否需要从缓存中读取图片是否有缓存从缓存中读取图片并set到target view中创建ImageViewAction对象setplaceholder设置Placeholder图片抛出IllegalStateException异常yesnoyesnoyesnoyesnoyesno

我们调用的一行代码已经分析完了,但似乎我们还是没有看到一张网络图片是如何加载进来的。其实,在分析上一段into方法时,最后的一步我们看到了该方法将创建出来的ImageViewAction对象通过enqueueAndSubmit方法交给了Picasso对象来进行处理,那么我们来看看这一步它具体做了什么。

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

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

可以看到,当我们传进来的ImageViewAction没有问题的时候,Picasso就将该action传给Dispatcher类来进行处理。那么我们接下来再看看Dispatcher做了什么:

    void dispatchSubmit(Action action) {
        handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
    }

改行代码里通过发送了一个REQUEST_SUBMIT消息到DispatchHandler对象中:

    case REQUEST_SUBMIT : {
        Action action = (Action) msg.obj;
        dispatcher.performSubmit(action);
        break;
    }
    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;
        }

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

在DisPatchHandler中,又通过performSubmit方法层层调用,最终创建出来了BitmapHunter对象,并放入线程池里执行。那么也就是说,我们的核心加载逻辑应该就在BitmapHunter的run方法中:

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

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

我们可以看到,最关键的result,也就是Bitmap对象,是通过hunt方法来获取的:

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

至此我们终于拿到了我们想要的图片了,而在BitmapHunter的run方法中我们拿到了图片以后则接着通过Dispatcher类分发完成事件最终通过ImageViewAction将Bitmap设置在我们的ImageView上。


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


void performComplete(BitmapHunter hunter) {
    ......
        batch(hunter);
    ......
    }


  private void batch(BitmapHunter hunter) {
      ......
        handler.sendEmptyMessageDelayed(HUNTER_DELAY_NEXT_BATCH,
            BATCH_DELAY);
      ......
}


void performBatchComplete() {
  ......
  mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(
      HUNTER_BATCH_COMPLETE, copy));
  ......
}


void complete(BitmapHunter hunter) {
      ......
            deliverAction(result, from, single);
      ...
}


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


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

终于,我们将辛辛苦苦得到的Bitmap设置到了我们的ImageView中了(上述代码过长,设计到多次分发跳转,所以我只是截取了里面关键的几行代码,有兴趣的朋友可以去对应的代码中去查看)。下面再梳理一下这个流程:

Created with Raphaël 2.1.0Dispatcher.dispatchCompleteDispatcher.peformCompleteDisaptcher.batchDispatcher.performBatchCompletePicasso.completePicasso.deliverActionAction.complete

最后通过这样的一个过程,图片就显示在了我们的ImageView中。

整个过程下来我们发现,加载一张图片远不是我们所看到的一行代码那么简单,中间还是经过了很多复杂的过程。此次分析主要是针对整个流程进行梳理,后面我会对其中每个流程中的一些关键技术做出详细的分析。