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

前言

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(“http://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) {
    //采用nanoTime()来得到开始的时间,比currentTimeMillis()更加准确。因为前者是精确到微秒为单位的,但是不能用这个来计算日期
        long started = System.nanoTime();
    //检查是否在主线程,不在主线程的话会抛出异常
        checkMain();

        if (target == null) {
            throw new IllegalArgumentException("Target must not be null.");
        }
    //创建RequestCreator对象时,我们会用uri和resourceId来构建一个Request.Builder对象,只有uri和resouceid都为空的时候,data.hasImage()会返回为false,然后取消这次加载图片的请求任务,将placeholder设置到ImageView中
        if (!data.hasImage()) {
            picasso.cancelRequest(target);
            if (setPlaceholder) {
                setPlaceholder(target, getPlaceholderDrawable());
            }
            return;
        }
    //当我们构建Picasso对象,设置了fit时,deferred为true,会将图片填充整个目标view,这里我们没有设置,所以不会走到该逻辑
        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 request = createRequest(started);
    //根据Request对象创建requestKey
        String requestKey = createKey(request);

    //判断是否需要从缓存中取值,目前我所分析的2.5.2的代码对于memoryPolicy赋值的方法已经被标为@Deprecated,所以默认我就认为所有的任务都应该从缓存中先取值
        if (shouldReadFromMemoryCache(memoryPolicy)) {
            Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
      //因为我们是首次加载,所以从缓存中取得的值为null
            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;
            }
        }

    //默认情况下setPlaceholder为true,我们可以通过placeholder来设置加载中的图片,如果不设置的话在加载的过程中就什么也不显示
        if (setPlaceholder) {
            setPlaceholder(target, getPlaceholderDrawable());
        }

    //最终经过千辛万苦我们终于可以创建出来一个ImageViewAction对象
        Action action = new ImageViewAction(picasso, target, request,
                memoryPolicy, networkPolicy, errorResId, errorDrawable,
                requestKey, tag, callback, noFade);

        //将ImageViewAction对象提交给Picasso对象进行处理
        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异常 yes no yes no yes no yes no yes no

picasso.enqueueAndSubmit(action)

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

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

可以看到,当我们传进来的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) {
    //如果action.getTag存在于pausedTags中的话,就放进pausedActions中,并取消此次请求
        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(图片猎人?好像挺好玩的样子)对象,我们是第一次加载图片,所以对象为空
        BitmapHunter hunter = hunterMap.get(action.getKey());
        if (hunter != null) {
            hunter.attach(action);
            return;
        }

    //如果线程池已经关闭的话就直接return
        if (service.isShutdown()) {
            if (action.getPicasso().loggingEnabled) {
                log(OWNER_DISPATCHER, VERB_IGNORED, action.request.logId(),
                        "because shut down");
            }
            return;
        }

    //创建BitmapHunter对象,并放入线程池中执行,存入hunterMap中
        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;
            }
        }

    //这里的retyCount是由RequestHandler在BitmapHunter构造函数中赋值而来的,因为是网络请求,所以用的是NetWorkRequestHandler,所赋值为2也就是说它会重试两次
        data.networkPolicy = retryCount == 0
                ? NetworkPolicy.OFFLINE.index
                : networkPolicy;
    //通过NetWorkRequestHandler从网络中加载图片
        RequestHandler.Result result = requestHandler.load(data, networkPolicy);
                    .......

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

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

//Dispatcher.java
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);
      ...
}

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

//ImageViewAction.java
  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.0 Dispatcher.dispatchComplete Dispatcher.peformComplete Disaptcher.batch Dispatcher.performBatchComplete Picasso.complete Picasso.deliverAction Action.complete

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

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值