Glide简析

随着Android开发的愈渐火热,各种Android的图片加载库也曾出不穷,比较有名的有:FrescoPicassoUniversal Image Loader等等。在这篇文章中,我会通过源码来简单地分析一下Glide使用时所发生的事情。

使用方法

对于Glide的使用方法不是本文的重点,在这里就不多说了,这里贴出Glide的Github地址,如果对使用方法有什么疑问的就上官方去看看吧。这里我们从Glide最简单的三行使用方法入手进行分析:

Glide.with(...)
        .load(...)
        .into(...);

流程分析

首先我们进入Glide类看看with()方法:

public static RequestManager with(Context context) {   
    RequestManagerRetriever retriever = RequestManagerRetriever.get(); 
    return retriever.get(context);
}

我们可以看到with()方法是Glide类中的一个静态方法,它会创建一个RequestManagerRetriever对象,在这里我们先不看这个类在创建过程中发生的事情,先看看它通过传入的Context对象所返回的这个RequestManager对象。

对于RequestManager这个类,官方文档是这样描述的:
A class for managing and starting requests for Glide. Can use activity, fragment and connectivity lifecycle events to intelligently stop, start, and restart requests. Retrieve either by instantiating a new object, or to take advantage built in Activity and Fragment lifecycle handling, use the static Glide.load methods with your Fragment or Activity.
本人英文一般,就不逐字逐句地翻译了。总之,对于RequestManager这个类的定位就是对图片加载请求进行管理的类,并且它会根据与其产生联系的Context对象的生命周期来管理图片加载的过程。因此,图片资源加载进ImageView的过程事实上是由它来一手掌管的。

知道了这些,我们接下来来看看它的load()方法,也就是我们将资源路径传入的这个方法,这里我们以传入一个Uri为例:

public DrawableTypeRequest load(Uri uri) {
    return (DrawableTypeRequest) fromUri().load(uri);
}

在这个方法中使用了DrawableTypeRequest中的load()方法去加载这个uri:

public DrawableRequestBuilder load(ModelType model) {    
    super.load(model);
    return this;
}

这个方法的泛型参数ModelType在这里所对应的实际类型就是我们传入的资源类型Uri,并且调用了DrawableRequestBuilder的父类方法load()来处理。

GenericRequestBuilder就是DrawableRequestBuilder的父类,这个类及其子类的作用就是用于请求加载的。我们来看看里面刚刚提到的load()方法:

public GenericRequestBuilder load(ModelType model) {
    this.model = model;
    isModelSet = true;
    return this;
}

这里我们发现,load()方法仅仅是将资源——这里就是我们的图片资源Uri赋值给了一个变量model,至于图片资源究竟是怎么加载进ImageView的,我们回到这里实际进行加载请求的类DrawableRequestBuilder去看看它当中被我们最后调用的into()方法:

public Target into(ImageView view) {
    return super.into(view);
}

load()方法相同,这里也调用了父类GenericRequestBuilderinto()方法:

public Target into(ImageView view) {
    ......
    return into(glide.buildImageViewTarget(view, transcodeClass));
}

对于这个方法我们只看最后一句代码。在这里又再次回到一开始的Glide,并调用了其中的buildImageViewTarget()方法,而在这个方法中传入了一个GlideDrawable对象transcodedClass

 Target buildImageViewTarget(ImageView imageView, Class transcodedClass) {
    return imageViewTargetFactory.buildTarget(imageView, transcodedClass);
}

我们继续跟踪下去:

public  Target buildTarget(ImageView view, Class clazz) {    
    if (GlideDrawable.class.isAssignableFrom(clazz)) {
        return (Target) new GlideDrawableImageViewTarget(view);
    } else if (Bitmap.class.equals(clazz)) {
        return (Target) new BitmapImageViewTarget(view);
    } else if (Drawable.class.isAssignableFrom(clazz)) {
        return (Target) new DrawableImageViewTarget(view);
    } else {
        throw new IllegalArgumentException("Unhandled class: " + clazz                + ", try .as*(Class).transcode(ResourceTranscoder)");
    }
}

经过反复地辗转我们终于发现了上面我们传入into()方法中的是一个和我们所要将图片加载进的ImageView相关的GlideDrawableImageViewTarget对象。我们先记住这一点,不继续深究下去,先回头看看那个GenericRequestBuilder中的into()方法:

public > Y into(Y target) {
    ......
    Request request = buildRequest(target);
    target.setRequest(request);
    ......
    requestTracker.runRequest(request);

    return target;
}

这段代码所做的事情根据方法名很容易就能猜到,它先根据传入的一个Target对象创建一个Request,并将两者建立关联,最后执行加载请求。

这里我们反过来会发现,这个Target的实际对象就是我们刚刚所说的那个GlideDrawable,另外谈到请求,是不是想到我们前面load()进去的那个Uri对象了呢?一阵云里雾里,整个内容终于联系了起来,那么我们就先来看看这个Request对象究竟是怎么创建的:

private Request buildRequest(Target target) {
    ......
    return buildRequestRecursive(target, null);
}

这里又将那个Target对象传进一个buildRequestRecursive()方法中:

private Request buildRequestRecursive(Target target, ThumbnailRequestCoordinator parentCoordinator) {
    ......
    return obtainRequest(target, sizeMultiplier, priority, parentCoordinator);
}

对于这个方法,我们重点来关注一下其中的一行代码,其中涉及了obtainRequest()方法,这个方法有四个参数,其中最重要的就是第一个,这里将刚刚的Target对象给传了进去,我们接下来看一下这个方法:

private Request obtainRequest(Target target,
        float sizeMultiplier, Priority priority,
        RequestCoordinator requestCoordinator) {
    return GenericRequest.obtain(
            loadProvider,
            model,
            signature,
            context,
            priority,
            target,
            sizeMultiplier,
            placeholderDrawable,
            placeholderId,
            errorPlaceholder,
            errorId,
            fallbackDrawable,
            fallbackResource,
            requestListener,
            requestCoordinator,
            glide.getEngine(),
            transformation,
            transcodeClass,
            isCacheable,
            animationFactory,
            overrideWidth,
            overrideHeight,
            diskCacheStrategy);
}

这个方法中只做了一件事,调用了GenericRequest类的静态方法obtain(),并且传入了很多的参数,这里注意其中的参数target,即上面的GlideDrawableImageViewTarget对象,另外还有就是这里执行了Glide中的getEngine()方法,还有资源模型model。然后继续往下看:

public static  GenericRequest obtain(
        LoadProvider loadProvider,
        A model,
        Key signature,
        Context context,
        Priority priority,
        Target target,
        float sizeMultiplier,
        Drawable placeholderDrawable,
        int placeholderResourceId,
        Drawable errorDrawable,
        int errorResourceId,
        Drawable fallbackDrawable,
        int fallbackResourceId,
        RequestListener requestListener,
        RequestCoordinator requestCoordinator,
        Engine engine,
        Transformation transformation,
        Class transcodeClass,
        boolean isMemoryCacheable,
        GlideAnimationFactory animationFactory,
        int overrideWidth,
        int overrideHeight,
        DiskCacheStrategy diskCacheStrategy) {
    @SuppressWarnings("unchecked")
    GenericRequest request = (GenericRequest) REQUEST_POOL.poll();
    if (request == null) {
        request = new GenericRequest();
    }
    request.init(loadProvider,
            model,
            signature,
            context,
            priority,
            target,
            sizeMultiplier,
            placeholderDrawable,
            placeholderResourceId,
            errorDrawable,
            errorResourceId,
            fallbackDrawable,
            fallbackResourceId,
            requestListener,
            requestCoordinator,
            engine,
            transformation,
            transcodeClass,
            isMemoryCacheable,
            animationFactory,
            overrideWidth,
            overrideHeight,
            diskCacheStrategy);
    return request;
}

这一段看上去有点长,但是其实也只涉及到了一个方法init(),这个方法同样接受了很多参数,并且在这个方法中,做的也只有一件事,就是将这些传入的参数一一赋值给GenericRequest的成员变量:

private void init(
        LoadProvider loadProvider,
        A model,
        Key signature,
        Context context,
        Priority priority,
        Target target,
        float sizeMultiplier,
        Drawable placeholderDrawable,
        int placeholderResourceId,
        Drawable errorDrawable,
        int errorResourceId,
        Drawable fallbackDrawable,
        int fallbackResourceId,
        RequestListener requestListener,
        RequestCoordinator requestCoordinator,
        Engine engine,
        Transformation transformation,
        Class transcodeClass,
        boolean isMemoryCacheable,
        GlideAnimationFactory animationFactory,
        int overrideWidth,
        int overrideHeight,
        DiskCacheStrategy diskCacheStrategy) {
    this.loadProvider = loadProvider;
    this.model = model;
    this.signature = signature;
    this.fallbackDrawable = fallbackDrawable;
    this.fallbackResourceId = fallbackResourceId;
    this.context = context.getApplicationContext();
    this.priority = priority;
    this.target = target;
    this.sizeMultiplier = sizeMultiplier;
    this.placeholderDrawable = placeholderDrawable;
    this.placeholderResourceId = placeholderResourceId;
    this.errorDrawable = errorDrawable;
    this.errorResourceId = errorResourceId;
    this.requestListener = requestListener;
    this.requestCoordinator = requestCoordinator;
    this.engine = engine;
    this.transformation = transformation;
    this.transcodeClass = transcodeClass;
    this.isMemoryCacheable = isMemoryCacheable;
    this.animationFactory = animationFactory;
    this.overrideWidth = overrideWidth;
    this.overrideHeight = overrideHeight;
    this.diskCacheStrategy = diskCacheStrategy;
    status = Status.PENDING;
    ......
}

到这里对于加载请求的设置几本完成,我们再回去看看那句运行加载的代码requestTracker.runRequest(request);所做的具体的事情:

public void runRequest(Request request) {
    ......
    if (!isPaused) {
        request.begin();
    } else {
        ......
    }
}

这里调用了刚刚设置好的Request对象的begin()方法,而这里的Request对象的实际类型就是上面我们所看到的GenericRequest对象。于是,我们来看看它的begin()方法:

public void begin() {
    ......
    if (!isComplete() && !isFailed() && canNotifyStatusChanged()) {
          target.onLoadStarted(getPlaceholderDrawable());
    }
    ......
}

这里我们需要关注的就是一个Target对象的onLoadStarted()方法,在这里我们记起这个Target对象的实际类型就是上面的init()方法中所设置的GlideDrawableImageViewTarget对象。也许你会认为这个begin()方法就是资源加载进ImageView的关键,但是当我们点进去查看它的begin()方法时却发现并不如我们所想,它只是为我们的ImageView设置了一个占位图,并没有做其他的事情。但是我们在查看GlideDrawableImageViewTarget的源码的时候,我们发现了这么一个方法onResourceReady(),在这个方法中有这么一句代码:

setResource(resource);

接着看看setResource()

public void setResource(GlideDrawable resource) {
    view.setImageDrawable(resource);
}

这里的resource我们猜应该就是图片资源了,也会是说这里所做的事情就是最后将图片呈现在ImageView上,但程序究竟是怎么到这里的呢,我们想到了上面的getEngine()方法,于是我们来看看这里所做的事情:

Engine getEngine() {
    return engine;
}

这个Engine又是一个非常重要的类,我们来看看这个类的官方介绍:
Responsible for starting loads and managing active and cached resources.
我们发现这个类就是真正用来管理加载的类。但是这个不是我这篇文章的重点,关于它所作的事情我会在后面的文章中对它进行简析。既然这个Engine对象是用来加载资源的,那么我们就想到了一开始的那个上面另外一个要记住的model,看看它们是怎么运用的。要想知道这到底是怎么使用的,我在这里贴出最重要的一段:

private void onLoadComplete(Resource resource) {
      manager.onResourceReady(resource);
}

这个方法是EngineRunnable类中的,这个类从名字就可以看出来它的作用就是响应Engine的。而这里的onResourceReady()则是触发了GenericRequest中的一个回调onResourceReady()

public void onResourceReady(Resource resource) {
    ......
    onResourceReady(resource, (R) received);
}

这里又调用了该类中的一个重载方法:

private void onResourceReady(Resource resource, R result) {
    ......
    if (requestListener == null || !requestListener.onResourceReady(result, model, target, loadedFromMemoryCache,
        isFirstResource)) {
        ......
    }
    notifyLoadSuccess();
    ......
}

这里我们看到了,这个方法使用到了model,而这个方法则属于一个RequestListener回调接口,这个回调接口究竟会在哪里被调用呢,其实就是我们上面提到的GlideDrawableImageViewTargetonResourceReady(),而在这个方法中,另一个参数target在这里的实际类型就是GlideDrawableImageViewTarget。到这里我们终于是弄明白整个图片资源的加载过程了。

这里用了大量的篇幅大致地给大家介绍了一下Glide的大致加载流程,但是在这其中我们还有很多关于图片加载的所必需弄懂的细节并没有进行介绍,但是这篇文章就先到这里,关于这些东西我会在后续的文章中尽我所能地分析给大家。

你可能感兴趣的:(Glide简析)