Glide源码阅读

声明

本文章是基于 glide 3.6.1的

个各类的功能介绍

1.Glide:向外暴露单例静态接口,构建Request.配置资源类型,缓存策略,图片处理等,可以直接通过该类完整简单的图片请求和填充,内部持有一些变量BitmapPool,MemoryCache,ByteArrayPool,便于低内存情况时自动清理内存

2.RequestManagerRetriever: (RequestManager的获取类 单例类)提供静态方法去创建新的RequestManager 或者从Activity或者fragment中检索已经存在的请求

3.RequestManager:(管理请求的类 实现了LiftcycleListener) 可以依赖Activity和Fragment的声明周期进行请求的start,stop,reStart等操作

4.RequestManagerFragment:(用于窃听Activity,Fragment页面的生命周期变化的)一个没有视图的Fragment,内部有RequestManager这个成员变量.每一个context(Activity或者Fragment)都会拥有一个RequestManagerFragment,用于监听Activity或者Fragment生命周期的变化,从而调用ActivityFragmentLifecycle的方法,当内存不足时会调用RequestManager的相关方法

5.ActivityFragmentLifecycle:(实现了Liftcycle接口)用于监听Activity和Fragment生命周期活动的实现类.

6.DrawableTypeRequest:(继承了DrawableRequestBuilder)一个用来创建加载请求的类,可以直接加载GIF动画,也可以直接加载Bitmap或者是资源文件

7.DrawableRequestBuilder:(继承了GenericRequestBuilder) 创建请求GlideDrawable请求的类

8.GenericRequestBuilder:就是一个通用类,实现了一些请求通用的方法

9.GenericRequest:(实现了Request接口)这是一个请求的封装类,会将资源加载到指定的目标身上

10.RequestTracker:用于跟踪,取消,重启 完成和失败请求的类,也就是说这个类可以对请求进行开启和暂停等操作

11.DataLoadProvider:(是一个接口) 一个负载提供程序,它提供了必要的编码器和解码器,以便从特定类型的数据中解码特定类型的资源。也就是一个内部集成了不同情况下的编解码器

12.LoadProvider:(是一个接口,他继承了DataLoadProvider)其实就是DataLoadProvide的扩展,在DataLoadProvide的基础上也支持了ModelLoader和ResourceTranscoder

13.ModelLoader:(是一个接口) 用具将复杂的数据类型转换为具体的数据类型,并且可以使用DataFetcher来获取资源数据--->ModelLoader 是一个工厂接口。将任意复杂的 model 转换为准确具体的可以被 DataFetcher 获取的数据类型。 每一个 model 内部实现了一个 ModelLoaderFactory,内部实现就是将 model 转换为 Data

14.DataFetcher:(是一个接口) 就是加载器的顶级接口

15.Engine:负责启动下载,管理活动和缓存资源的类-->任务创建,发起,回调,管理存活和缓存的资源

16.EngineJob:(负责加载每一个请求,它里面有线程池成员变量)下载的管理类,也就是Engine的管理类--->将线程回调到主线程的类

17.EngineRunnable:(实现了Runnable接口) 就是一个任务,在下载完成后或者找到缓存图片后进行解码

18.DecodeJob:调度任务的核心类,整个请求的繁重工作都在这里完成,处理来自缓存或者原始的资源,应用转换动画以及 transcode

19.HttpUrlFetcher:(实现了DataFetcher) 该类是专门从网络中加载图片的加载器.

20.EngineRunnableManager:(是一个接口,继承了ResourceCallback)用于监听图片获取成功的监听器,

21.ResourceCallback:(是一个接口)用于监听资源是否加载成功或者失败的回到

22.Target:(是一个接口)request 的载体,各种资源对应的加载类,含有生命周期的回调方法,方便开发人员进行相应的准备以及资源回收工作

23.Resource:(是一个接口)对资源进行包装的接口,提供 get,recycle,getSize,以及原始类的 getResourceClass 方法。 其实现类都在resource包下,resource 包下也就是各种资源:bitmap,bytes,drawable,file,gif,以及相关解码器,转换器

Glide.with(this).load("...imageurl..").into(iv);这段代码内部调用流程如下

首先上段代码可以分解为

    RequestManager requestManager = Glide.with(this);
    DrawableTypeRequest<String> drawableTypeRequest = requestManager .load("...imageurl..");
    drawableTypeRequest .into(iv);

首先我们先来看看 RequestManager requestManager = Glide.with(this); 这段代码

1.Glide.with()方法中会调用RequestManagerRetriever的静态get()方法获取到RequestManagerRetriever的实例,然后调用RequestManagerRetriever的get()方法获取到RequestManager的实例并返回

public static RequestManager with(FragmentActivity activity) {
    RequestManagerRetriever retriever = RequestManagerRetriever.get();
    return retriever.get(activity);
}

2.在RequestManagerRetriever的get()方法中有一个重要的操作就是给当前的activity也就是Glide.with()方法中传入的activity添加一个SupportRequestManagerFragment(继承自Fragment TAG 为"com.bumptech.glide.manager")用于监控传入activity的声明周期变化,从而让Glide的操作达到和Activity的声明周期一致的状态.还有一个重要的操作就是在RequestManager的构造方法中将ActivityFragmentLifecycle和Lifecycle(RequestManager)进行了绑定,也就是说将传入Activity的生命周期传入到了RequestManager中(这个过程下面有具体的分析) ** RequestManager requestManager = Glide.with(this); **

public RequestManager get(FragmentActivity activity) {
    if (Util.isOnBackgroundThread()) {
        return get(activity.getApplicationContext());
    } else {
        assertNotDestroyed(activity);
        //获取到的当前Activity的FragmentManager并传入给下面方法
        FragmentManager fm = activity.getSupportFragmentManager();
        return supportFragmentGet(activity, fm);
    }
}


RequestManager supportFragmentGet(Context context, FragmentManager fm) {
    //获取到SupportRequestManagerFragment实例并使用FragmentManager添加到当前Activity中
    SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm);
    RequestManager requestManager = current.getRequestManager();
    if (requestManager == null) {
        //创建RequestManager并设置到SupportRequestManagerFragment中保存起来
        requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode());
        current.setRequestManager(requestManager);
    }
    return requestManager;
}


RequestManager(Context context, final Lifecycle lifecycle, RequestManagerTreeNode treeNode,
        RequestTracker requestTracker, ConnectivityMonitorFactory factory) {
    this.context = context.getApplicationContext();
    this.lifecycle = lifecycle;
    this.treeNode = treeNode;
    this.requestTracker = requestTracker;
    this.glide = Glide.get(context);
    this.optionsApplier = new OptionsApplier();

    ConnectivityMonitor connectivityMonitor = factory.build(context,
            new RequestManagerConnectivityListener(requestTracker));

        // 在这里将传入的Activity的生命周期传到了RequestManager身上
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                lifecycle.addListener(RequestManager.this);
            }
        });
    } else {
        lifecycle.addListener(this);
    }
    lifecycle.addListener(connectivityMonitor);
}

看完这些代码以后我们来捋一捋到底RequestManager是如何获取到传入的Activity的生命周期的,

首先在执行RequestManagerRetriever的get()方法的时候会给传入的Activity设置一个没有视图的Fragment也就是SupportRequestManagerFragment,在SupportRequestManagerFragment中有一个成员变量是ActivityFragmenLifecycle它实现了Lifecycle接口是专门用来监视SupportRequestmanagerFragment的生命周期的,其实这个声明周期也就是传入的Activity的生命周期.在ActivityFragmentLifecycle中有一个存储着LifecycleListener的Set集合.当Activity的生命周期方法被调用的时候在SupportRequestManagerFragment中也会调用ActivityFragmentLifecycle的方法,然后ActivityFragmentLifecycle在调用LifecycleListener的方法,而刚好RequestManager实现了LifecycleListener这个接口,所以从这里生命周期就传到了RequestManager的身上.

在这里ActivityFragmentLifecycle是一个被观察者,RequestManager是一个观察者他们的绑定是在RequestManager的构造方法中.

    .....
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            lifecycle.addListener(RequestManager.this);
        }
    });
    .....

如下图所示

glide获取声明周期流程图.jpg

下来我们再看看 DrawableTypeRequest<String> drawableTypeRequest = requestManager .load("...imageurl.."); 这段代码

1.这里首先调用了RequestManager的load()方法,然后在RequestManager中调用fromString()方法,然后在fromString()中调用loadGeneric()方法创建一个DrawableTypeRequest,然后右调用了DrawableTypeRequest方法并返回

public DrawableTypeRequest<String> load(String string) {
    return (DrawableTypeRequest<String>) fromString().load(string);
}

public DrawableTypeRequest<String> fromString() {
    return loadGeneric(String.class);
}

private <T> DrawableTypeRequest<T> loadGeneric(Class<T> modelClass) {
    ModelLoader<T, InputStream> streamModelLoader = Glide.buildStreamModelLoader(modelClass, context);
    ModelLoader<T, ParcelFileDescriptor> fileDescriptorModelLoader =
            Glide.buildFileDescriptorModelLoader(modelClass, context);
    if (modelClass != null && streamModelLoader == null && fileDescriptorModelLoader == null) {
        throw new IllegalArgumentException("Unknown type " + modelClass + ". You must provide a Model of a type for"
                + " which there is a registered ModelLoader, if you are using a custom model, you must first call"
                + " Glide#register with a ModelLoaderFactory for your custom model class");
    }

    return optionsApplier.apply(
            new DrawableTypeRequest<T>(modelClass, streamModelLoader, fileDescriptorModelLoader, context,
                    glide, requestTracker, lifecycle, optionsApplier));
}

@Override
public DrawableRequestBuilder<ModelType> load(ModelType model) {
    super.load(model);
    return this;
}

其实load()方法干的事儿很简单,就是根据load()方法中传入的不同类型的值,来生成不同的DrawableTypeRequest并进行返回

最后我们来看看 drawableTypeRequest .into(iv); 这段代码

1.首先会调用DrawableTypeRequest中的into方法,其实是DrawableRequestBuilder的into方法,因为DrawableTypeRequest继承了DrawableRequestBuilder而且没有重写into方法,然后在调用DrawableRequestBuilder的父类GenericRequestBuilder的into方法,然后在调用GenericRequestBuilder中的into的重载方法,在这个into方法中首先会判断 传入的ImageView是否已经携带请求,如果携带请求就将这个请求清除掉,再加上新的请求,(这就解决了listView中图片错位的现象).

2.下来就会调用buildRequest()方法去创建一个请求

3.buildRequest()方法中会调用buildRequestRecursive()方法去创建一个请求

4.buildRequestRecursive()方法中回到用obtainRequest()方法去真正的创建一个请求在该方法中回去判断是否先加载随略图,如果是则会创建一个载缩略图请求和一个原始尺寸的请求否则只创建原始尺寸的请求

5.obtainRequest()方法中调用 GenericRequest中obtain()方法

6.在obtain()方法中会调用init()方法对请求进行初始化 这一上2-6步骤都是在创建一个请求.

7.在执行完buildRequest()方法以后,下面就执行了RequestTracker 的runRequest(Request request)方法

8.在runRequest(Request request)方法中 调用了Request的begin()方法,因为GenericRequest就是实现了Request接口,所以也就是GenericRequest的begin()方法

9.在begin()方法中执行了onSizeReady()方法

10.onSizeReady()方法中首先调用ModelLoader.getResourceFetcher发方法去获取对应资源的加载器,然后调用Engine.load()方法开始加载

11.Engine.load()方法也是先从内存中找 ,然后在本地找最后在从网络下载,执行下载流程的话首先会获取到EngineJob的实例

12.创建一个工作线程 EngineRunnable用于解码下载得到的流或者是缓存中找的的图片

13.将EngineRunnable添加到EngineJob中开始执行

14.EngineRunnable既然已经开始执行那我们就来看看他的run方法,在run方法中首先会调用decode()方法,在decode方法中首先会判断是否从缓存中找,我们这里直接看在网络中下载的流程,所以这里走的是decodeFromSource()

15.decodeFromSource()中又调用了DecodeJob的decodeFromSource()方法

16.在DecodeFromSource方法中又调用了decodeSource()方法

17.decodeSource()方法中调用了一个重要的方法,fetcher.loadData()这个方法就是从不同的途径中找到我们要的图片,比如缓存或者网络,这里的fetcher就是HttpUrlFetcher

18.HttpUrlFetcher的loadData()方法会调用loadDataWithRedirects()方法,在这个方法中我们看到了久违的HttpUrlConnection,也就是说Glide这个框架是从这里进行联网请求图片的,最后这个方法返回一个流对象,然后loadData()也返回了一个流对象到DecodeJob的decodeSource()方法中

19.然后在DecodeJob的decodeSource()中对返回的这个流对象使用decodeFromSourceData()方法进行包装,包装成Resource对象进行返回,返回到DecodeJob的decodeFromSource()方法中.

20DecodeJob的decodeFromSource()方法中再调用transformEncodeAndTranscode()方法.

21.在transformEncodeAndTranscode()方法中会调用writeTransformedToCache()方法将获得的流对象缓存到硬盘中.

22.缓存完以后调用transcode()方法将获得的流对象进行转化然后进行返回,返回到EngineRunnabl的decodeFormSource()中.

24.然后在返回到EngineRunnable的Decode()方法中

25.然后再返回到EngineRunnable的run()方法中

26.然后在run()方法中执行onLoadComplete()方法

27.然后执行了EngineRunnableManager的onResourceReady()方法,因为实现了EngineRunnableManager接口的只有EngineJob,所以这里执行的是EngineJob的OnResourceReady()方法

28.在EngineJob的OnResourceReady()方法中做了一件重要的事情,就是使用主线程的Handler将线程切换到主线程中

29.然后进入到了EngineJob的MainTreadCallback类的handleMessage()方法中,在加载成功的情况下回执行EngineJob中的handleResultOnMainThread()方法

30.在EngineJob的handleResultOnMainThread()方法中会循环调用ResourceCallBack的OnResourceReady()方法,因为GenericRequest实现了RequestCallback接口,所以就执行了GenericRequest的onResourceReady()方法

31.在GenericRequest的onResourceReady()方法中调用了Target的onResourceReady()方法,因为这里我们传入的是ImageView,所以这里的Target是ImageViewTarget,所以也就是ImageViewTarget的onResourceReady.

32.ImageViewTarget的onResourceReady中有调用了setResource()方法这是一个抽象方法,所以我们随便看一个他的子类是怎么实现的,比如DrawableImageViewTarget中就是调用 view.setImageDrawable(resource); 方法将Bitmap设置到ImageView中.到此为止整个加载流程就完毕了.

//DrawableRequestBuilder中
@Override
public Target<GlideDrawable> into(ImageView view) {
    return super.into(view);
}



//GenericRequestBuilder中
public Target<TranscodeType> into(ImageView view) {
    ............
    return into(glide.buildImageViewTarget(view, transcodeClass));
}



//GenericRequestBuilder中
public <Y extends Target<TranscodeType>> Y into(Y target) {
    ..........
    Request previous = target.getRequest();
    //如果传入的ImageView已经携带请求就像这个请求给清除
    if (previous != null) {
        previous.clear();
        requestTracker.removeRequest(previous);
        previous.recycle();
    }

    //创建了一个请求
    Request request = buildRequest(target);
    target.setRequest(request);
    lifecycle.addListener(target);
    //开始执行这个请求
    requestTracker.runRequest(request);

    return target;
}



//GenericRequestBuilder中
private Request buildRequest(Target<TranscodeType> target) {
    if (priority == null) {
        priority = Priority.NORMAL;
    }
    return buildRequestRecursive(target, null);
}



//GenericRequestBuilder中
private Request buildRequestRecursive(Target<TranscodeType> target, ThumbnailRequestCoordinator parentCoordinator) {
    ..........
else if (thumbSizeMultiplier != null) {
        // Base case: thumbnail multiplier generates a thumbnail request, but cannot recurse.

        ThumbnailRequestCoordinator coordinator = new ThumbnailRequestCoordinator(parentCoordinator);
//创建一个原始尺寸的请求
        Request fullRequest = obtainRequest(target, sizeMultiplier, priority, coordinator);
//创建一个缩略图请求
        Request thumbnailRequest = obtainRequest(target, thumbSizeMultiplier, getThumbnailPriority(), coordinator);
        coordinator.setRequests(fullRequest, thumbnailRequest);
        return coordinator;
    } else {
//去建造一个原始尺寸的请求
 return obtainRequest(target, sizeMultiplier, priority, parentCoordinator);
    ..........
}



//GenericRequestBuilder中
 private Request obtainRequest(Target<TranscodeType> 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中
 public static <A, T, Z, R> GenericRequest<A, T, Z, R> obtain(
        LoadProvider<A, T, Z, R> loadProvider,
        A model,
        Key signature,
        Context context,
        Priority priority,
        Target<R> target,
        float sizeMultiplier,
        Drawable placeholderDrawable,
        int placeholderResourceId,
        Drawable errorDrawable,
        int errorResourceId,
        Drawable fallbackDrawable,
        int fallbackResourceId,
        RequestListener<? super A, R> requestListener,
        RequestCoordinator requestCoordinator,
        Engine engine,
        Transformation<Z> transformation,
        Class<R> transcodeClass,
        boolean isMemoryCacheable,
        GlideAnimationFactory<R> animationFactory,
        int overrideWidth,
        int overrideHeight,
        DiskCacheStrategy diskCacheStrategy) {
    @SuppressWarnings("unchecked")
    GenericRequest<A, T, Z, R> request = (GenericRequest<A, T, Z, R>) REQUEST_POOL.poll();
    if (request == null) {
//创建请求 
        request = new GenericRequest<A, T, Z, R>();
    }
//初始化请求
    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);
//将请求返回 最终返回到到GenericRequestBuilder的into()方法中,然后执行  requestTracker.runRequest(request);这句代码,开始执行请求
    return request;
}



//RequestTracker中
public void runRequest(Request request) {
    requests.add(request);
    if (!isPaused) {
//开始执行请求
        request.begin();
    } else {
        pendingRequests.add(request);
    }
}



//GenericRequest中
@Override
public void begin() {
   ......
    if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
//当ImageView的大小已经确定
        onSizeReady(overrideWidth, overrideHeight);
    } else {
        target.getSize(this);
    }
   ......
}



//GenericRequest中
 @Override
public void onSizeReady(int width, int height) {
   ......
    ModelLoader<A, T> modelLoader = loadProvider.getModelLoader();
    final DataFetcher<T> dataFetcher = modelLoader.getResourceFetcher(model, width, height);

   ......
    ResourceTranscoder<Z, R> transcoder = loadProvider.getTranscoder();
   ......
    loadedFromMemoryCache = true;
    //开始加载图片
    loadStatus = engine.load(signature, width, height, dataFetcher, loadProvider, transformation, transcoder,
            priority, isMemoryCacheable, diskCacheStrategy, this);
    loadedFromMemoryCache = resource != null;
   ......
}



//Engine中
 public <T, Z, R> LoadStatus load(Key signature, int width, int height, DataFetcher<T> fetcher,
        DataLoadProvider<T, Z> loadProvider, Transformation<Z> transformation, ResourceTranscoder<Z, R> transcoder,
        Priority priority, boolean isMemoryCacheable, DiskCacheStrategy diskCacheStrategy, ResourceCallback cb) {
    Util.assertMainThread();
    long startTime = LogTime.getLogTime();

    final String id = fetcher.getId();
    EngineKey key = keyFactory.buildKey(id, signature, width, height, loadProvider.getCacheDecoder(),
            loadProvider.getSourceDecoder(), transformation, loadProvider.getEncoder(),
            transcoder, loadProvider.getSourceEncoder());
//从缓存中加载
    EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
    if (cached != null) {
        cb.onResourceReady(cached);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Loaded resource from cache", startTime, key);
        }
        return null;
    }

    EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
    if (active != null) {
        cb.onResourceReady(active);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Loaded resource from active resources", startTime, key);
        }
        return null;
    }

    EngineJob current = jobs.get(key);
    if (current != null) {
        current.addCallback(cb);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Added to existing load", startTime, key);
        }
        return new LoadStatus(cb, current);
    }

    EngineJob engineJob = engineJobFactory.build(key, isMemoryCacheable);
    DecodeJob<T, Z, R> decodeJob = new DecodeJob<T, Z, R>(key, width, height, fetcher, loadProvider, transformation,
            transcoder, diskCacheProvider, diskCacheStrategy, priority);
//创建从网络加载图片的线程
    EngineRunnable runnable = new EngineRunnable(engineJob, decodeJob, priority);
    jobs.put(key, engineJob);
    engineJob.addCallback(cb);
//启动线程下载图片,启动线程后就会进入到EngineRunnable的run()方法
    engineJob.start(runnable);

    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logWithTimeAndKey("Started new load", startTime, key);
    }
    return new LoadStatus(cb, engineJob);
}



//EngineRunnable中
 @Override
public void run() {
    if (isCancelled) {
        return;
    }

    Exception exception = null;
    Resource<?> resource = null;
    try {
//进行下载
        resource = decode();
    } catch (Exception e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "Exception decoding", e);
        }
        exception = e;
    }

    ........

    if (resource == null) {
        onLoadFailed(exception);
    } else {
//当下载成功
        onLoadComplete(resource);
    }
}



//EngineRunnable中
private Resource<?> decode() throws Exception {
    if (isDecodingFromCache()) {
//从缓存中加载
        return decodeFromCache();
    } else {
//从网络中加载
        return decodeFromSource();
    }
}



//EngineRunnable中
private Resource<?> decodeFromSource() throws Exception {
    return decodeJob.decodeFromSource();
}



//DecodeJob中
public Resource<Z> decodeFromSource() throws Exception {
    Resource<T> decoded = decodeSource();
    return transformEncodeAndTranscode(decoded);
}


//DecodeJob中
private Resource<T> decodeSource() throws Exception {
    Resource<T> decoded = null;
    try {
        long startTime = LogTime.getLogTime();
//使用加载器去网络中加载图片
        final A data = fetcher.loadData(priority);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Fetched data", startTime);
        }
        if (isCancelled) {
            return null;
        }
//对结果进行包装
        decoded = decodeFromSourceData(data);
    } finally {
        fetcher.cleanup();
    }
    return decoded;
}



//HttpUrlFetcher中
@Override
public InputStream loadData(Priority priority) throws Exception {
    return loadDataWithRedirects(glideUrl.toURL(), 0 /*redirects*/, null /*lastUrl*/, glideUrl.getHeaders());
}



//HttpUrlFetcher中
//这里是真正使用HttpURLConnection下载图片的地方,
//最后将结果返回,在经过各种包装最终返回到EngineRunnable中调用onLoadComplete(resource);执行加载成功后的流程
 private InputStream loadDataWithRedirects(URL url, int redirects, URL lastUrl, Map<String, String> headers)
        throws IOException {
    if (redirects >= MAXIMUM_REDIRECTS) {
        throw new IOException("Too many (> " + MAXIMUM_REDIRECTS + ") redirects!");
    } else {
        // Comparing the URLs using .equals performs additional network I/O and is generally broken.
        // See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html.
        try {
            if (lastUrl != null && url.toURI().equals(lastUrl.toURI())) {
                throw new IOException("In re-direct loop");
            }
        } catch (URISyntaxException e) {
            // Do nothing, this is best effort.
        }
    }
    urlConnection = connectionFactory.build(url);
    for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
      urlConnection.addRequestProperty(headerEntry.getKey(), headerEntry.getValue());
    }
    urlConnection.setConnectTimeout(2500);
    urlConnection.setReadTimeout(2500);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);

    // Connect explicitly to avoid errors in decoders if connection fails.
    urlConnection.connect();
    if (isCancelled) {
        return null;
    }
    final int statusCode = urlConnection.getResponseCode();
    if (statusCode / 100 == 2) {
        return getStreamForSuccessfulRequest(urlConnection);
    } else if (statusCode / 100 == 3) {
        String redirectUrlString = urlConnection.getHeaderField("Location");
        if (TextUtils.isEmpty(redirectUrlString)) {
            throw new IOException("Received empty or null redirect url");
        }
        URL redirectUrl = new URL(url, redirectUrlString);
        return loadDataWithRedirects(redirectUrl, redirects + 1, url, headers);
    } else {
        if (statusCode == -1) {
            throw new IOException("Unable to retrieve response code from HttpUrlConnection.");
        }
        throw new IOException("Request failed " + statusCode + ": " + urlConnection.getResponseMessage());
    }
}



//EngineRunnable中
private void onLoadComplete(Resource resource) {\
    //这里的manager是EngineRunnableManager,实现了这个接口的只有EngineJob,也就是说调用的是EngineJob中国的onRequestReady()方法
    manager.onResourceReady(resource);
}



//EngineJob中
@Override
public void onResourceReady(final Resource<?> resource) {
    this.resource = resource;
//使用Handler将结果发送到主线程中 ,结果会在EngineJob中的内部类MainThreadCallBack中收到       MAIN_THREAD_HANDLER.obtainMessage(MSG_COMPLETE, this).sendToTarget();
}



//EngineJob中
private static class MainThreadCallback implements Handler.Callback {

    @Override
    public boolean handleMessage(Message message) {
        if (MSG_COMPLETE == message.what || MSG_EXCEPTION == message.what) {
            EngineJob job = (EngineJob) message.obj;
            if (MSG_COMPLETE == message.what) {
//接收到成功的消息
                job.handleResultOnMainThread();
            } else {
//接收到失败的消息
                job.handleExceptionOnMainThread();
            }
            return true;
        }

        return false;
    }
}



//EngineJob中
 private void handleResultOnMainThread() {
    if (isCancelled) {
        resource.recycle();
        return;
    } else if (cbs.isEmpty()) {
        throw new IllegalStateException("Received a resource without any callbacks to notify");
    }
    engineResource = engineResourceFactory.build(resource, isCacheable);
    hasResource = true;

    // Hold on to resource for duration of request so we don't recycle it in the middle of notifying if it
    // synchronously released by one of the callbacks.
    engineResource.acquire();
    listener.onEngineJobComplete(key, engineResource);

  //循环接口集合,调用接口的onResourceReady()方法,通知资源已经加载完毕,因为GenericRequest实现了该接口,
//所以GenericRequest的onResourceReady()方法会被电泳
    for (ResourceCallback cb : cbs) {
        if (!isInIgnoredCallbacks(cb)) {
            engineResource.acquire();
            cb.onResourceReady(engineResource);
        }
    }
    // Our request is complete, so we can release the resource.
    engineResource.release();
}


//GenericRequest中
 @Override
public void onResourceReady(Resource<?> resource) {

.......

    if (!canSetResource()) {
        releaseResource(resource);
        // We can't set the status to complete before asking canSetResource().
        status = Status.COMPLETE;
        return;
    }
    
//调用重载方法onResourceReady()
    onResourceReady(resource, (R) received);
}



//GenericRequest中
private void onResourceReady(Resource<?> resource, R result) {
    // We must call isFirstReadyResource before setting status.
    boolean isFirstResource = isFirstReadyResource();
    status = Status.COMPLETE;
    this.resource = resource;

    if (requestListener == null || !requestListener.onResourceReady(result, model, target, loadedFromMemoryCache,
            isFirstResource)) {
        GlideAnimation<R> animation = animationFactory.build(loadedFromMemoryCache, isFirstResource);
    //调用Target子类的OnResourceReady()方法将图片加载到ImageView上
        target.onResourceReady(result, animation);
    }

    notifyLoadSuccess();

    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logV("Resource ready in " + LogTime.getElapsedMillis(startTime) + " size: "
                + (resource.getSize() * TO_MEGABYTE) + " fromCache: " + loadedFromMemoryCache);
    }
}



//BitmapImageViewTarget中
@Override
public void onResourceReady(Z resource, GlideAnimation<? super Z> glideAnimation) {
    if (glideAnimation == null || !glideAnimation.animate(resource, this)) {
        setResource(resource);
    }
}

//BitmapImageViewTarget中
@Override
protected void setResource(Bitmap resource) {
  //调用Android API将资源加载到ImageView上 
    view.setImageBitmap(resource);
}

Glide Engine中into()方法的流程图

Engine_into().jpg

Glide加载图片的总流程图

glide_uml.png
Glide.png
glide加载图片流程.png

几个问题

1.glide中的线程池的核心线程数有几个
glide中线程池的初始化是在GlideBuilder中的createGlide中的,glide中的线程池有两种,一个是sourceService他的核心线程数是CPU核心数,最大线程数也是CPU核心数,另一个是diskCacheService他的核心线程数是1,最大线程数也是1.为什么会核心线程数和最大线程数是一样的?我们可以去看看FifoPriorityThreadPoolExecutor的构造方法,这两个线程池都是FifoPriorityThreadPoolExecutor,该线程池使用的是PriorityBlockingQueue这种阻塞队列,该队列是具有优先级而且空间无限的队列.所以也就是说这种线程池只有核心线程,是一种依赖优先级的线程池,又来执行glide的加载,解码和转换任务.sourceService和diskCacheService两个线程池的区别是,sourceService是当缓存中没有展示的对象时使用,而diskCacheService是缓存中存在展示对象时使用

Glide createGlide() {
    if (sourceService == null) {
        final int cores = Math.max(1, Runtime.getRuntime().availableProcessors());
//依赖于优先级的线程池,用来执行Glide的加载,解码和转换任务(当从缓存中没有找到对应的对象时)
//线程数是CPU核心数
        sourceService = new FifoPriorityThreadPoolExecutor(cores);
    }
    if (diskCacheService == null) {
//依赖于优先级的线程池,用来执行Glide的加载,解码和转换任务(当从缓存中有对应的对象时)
//线程数量为1
        diskCacheService = new FifoPriorityThreadPoolExecutor(1);
    }
.....

public FifoPriorityThreadPoolExecutor(int poolSize) {
    this(poolSize, UncaughtThrowableStrategy.LOG);
}

/**
 * Constructor to build a fixed thread pool with the given pool size using
 * {@link com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor.DefaultThreadFactory}.
 *
 * @param poolSize The number of threads.
 * @param uncaughtThrowableStrategy Dictates how the pool should handle uncaught and unexpected throwables
 *                                  thrown by Futures run by the pool.
 */
public FifoPriorityThreadPoolExecutor(int poolSize, UncaughtThrowableStrategy uncaughtThrowableStrategy) {
    this(poolSize, poolSize, 0, TimeUnit.MILLISECONDS, new DefaultThreadFactory(),
        uncaughtThrowableStrategy);
}

public FifoPriorityThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAlive, TimeUnit timeUnit,
        ThreadFactory threadFactory, UncaughtThrowableStrategy uncaughtThrowableStrategy) {
    super(corePoolSize, maximumPoolSize, keepAlive, timeUnit, new PriorityBlockingQueue<Runnable>(), threadFactory);
    this.uncaughtThrowableStrategy = uncaughtThrowableStrategy;
}

2.glide中图片的默认格式
图片的默认格式是RGB-565

//DecodeFormat中
/** The default value for DecodeFormat. */
public static final DecodeFormat DEFAULT = PREFER_RGB_565;

3.glide的加载策略,glide的加载策略也是按照 内存->硬盘->网络的顺序来的,但是他比其他的框架做的更细化一些,首先他会去内存中找,如果没有他会从最近活跃的资源中找,然后还会去下载队列中去找,最后才是去下载

  /** 
 *  1. 检查内存缓存
 *  2. 检查最近的活跃资源
 *  3. 检查最近的加载任务
 *  4.去网络中下载
 *  活跃资源指的是那些不止一次被加载并没有进行过资源释放的图片,一旦被释放,
 *  那么该资源则会从近期活跃资源中删除并进入到内存缓存中,
 *  但是如果该资源再次从内存缓存中读取,则会重新添加到活跃资源中
 */
public <R> LoadStatus load( 
GlideContext glideContext, 
Object model,    
Key signature,
int width,
int height,
Class<?> resourceClass,
Class<R> transcodeClass,
Priority priority,
DiskCacheStrategy diskCacheStrategy,    
Map<Class<?>, Transformation<?>> transformations,    
boolean isTransformationRequired,    
Options options,    
boolean isMemoryCacheable,    
ResourceCallback cb) {  

Util.assertMainThread();  
long startTime = LogTime.getLogTime();  
//内存缓存的唯一键值
EngineKey key = keyFactory.buildKey(model, signature,     width, height, transformations, resourceClass,   transcodeClass, options); 
//首先从缓存中查找
EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);  
if (cached != null) {    
 cb.onResourceReady(cached,   DataSource.MEMORY_CACHE);    
...  
  return null;  
}  
//如果缓存中没有找到,则去活跃资源中加载
//memCache中该bitmap则会被remove掉bitmap并进入activeResource中
EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);  
if (active != null) {    
 cb.onResourceReady(active, DataSource.MEMORY_CACHE);    
 ...   
}    
 return null;  
}  
//如果该任务之前已经在队列中,则添加新的callback,然后返回
EngineJob current = jobs.get(key);  
if (current != null) {    
current.addCallback(cb);    
...   
return new LoadStatus(cb, current);  
}  
//如果是新的加载任务,先创建EngineJob和DecodeJob,然后开始任务
EngineJob<R> engineJob = engineJobFactory.build(key, isMemoryCacheable);  
DecodeJob<R> decodeJob = decodeJobFactory.build(glideContext,model,key,signature,width,height,resourceClass,transcodeClass,      priority,diskCacheStrategy,transformations,      isTransformationRequired,options,engineJob); 
jobs.put(key, engineJob);  
engineJob.addCallback(cb);  
//开始任务
engineJob.start(decodeJob);  
...
return new LoadStatus(cb, engineJob);
}

4.glide的diskLruCache的默认缓存路径在哪里,默认缓存容量是多少?
在项目的cache目录image_manager_disk_cache文件夹下,容量是250M

    //DiskCache中
    /** 250 MB of cache. */
    int DEFAULT_DISK_CACHE_SIZE = 250 * 1024 * 1024;
    String DEFAULT_DISK_CACHE_DIR = "image_manager_disk_cache";

5.diskLruCache的四种缓存策略
DiskCacheStrategy.NONE :不缓存图片
DiskCacheStrategy.SOURCE :缓存图片源文件
DiskCacheStrategy.RESULT:缓存修改过的图片
DiskCacheStrategy.ALL:缓存所有的图片,默认

  1. 使用thumbnail(0.1f)//设置缩略图, 以后Glide 会先去请求缩略图,然后在请求 原图,因为缩略图一般比较小所以请求的比较快.

7.如果一个应用中有多个地方要使用同一张照片,但是可能尺寸有可能不一样,那么我们只需要设置所有地方的Glide的磁盘缓存策略为 Source就可以使用一张照片了(因为你缓存的是source,那么去查找缓存的时候肯定找的也是source了)

总结

Glide加载图片,首先会在内存中找,如果内存中没有就去最近本地磁盘中找,然后磁盘中没有的话会去,任务队列中找有没有正在加载下载此图片的任务,如果也没有那就会使用HttpURLConnaction进行下载,现在完成后就会用new Handler(Loop.getMainLooper)获取到主线程的Handler然后将获取到的图片发送到主线程中.

参考文章

http://www.cnblogs.com/guanmanman/p/7008259.html
这篇文章讲的更细一点http://www.jianshu.com/p/7125feef0ddf

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,029评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,395评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,570评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,535评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,650评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,850评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,006评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,747评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,207评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,536评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,683评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,342评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,964评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,772评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,004评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,401评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,566评论 2 349

推荐阅读更多精彩内容