Gilde源码分析

with()过程

Glide的实现

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

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//不急着看,会有回头的时候
 Target buildImageViewTarget(ImageView imageView, Class transcodedClass) {
    return imageViewTargetFactory.buildTarget(imageView, transcodedClass);
}

public class ImageViewTargetFactory {
    //将ImageView包装成一个GlideDrawableImageViewTarget对象
    //回到into过程看看这个包装类的实现
    @SuppressWarnings("unchecked")
    public  Target buildTarget(ImageView view, Class clazz) {
        return (Target) new GlideDrawableImageViewTarget(view);
    }
}

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//获取一个Engine对象
//虽然实际上不是这样实现的,但是是这么个意思
Engine getEngine() {
    if (engine == null) {
        engine = new Engine(memoryCache, diskCacheFactory, diskCacheService, sourceService);
    }
    return engine;
}


RequestManagerRetriever的实现

public class RequestManagerRetriever implements Handler.Callback {

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    public RequestManager get(FragmentActivity activity) {
        if (Util.isOnBackgroundThread()) {
            return get(activity.getApplicationContext());
        } else {
            assertNotDestroyed(activity);
            FragmentManager fm = activity.getSupportFragmentManager();
            return supportFragmentGet(activity, fm);
        }
    }
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    RequestManager supportFragmentGet(Context context, FragmentManager fm) {
        //1.获取一个SupportRequestManagerFragment对象
        SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm);
        //2.通过Fragment获取一个其中的RequestManager对象
        RequestManager requestManager = current.getRequestManager();
        if (requestManager == null) {
            //创建一个新的requestManager对象
            //注意current.getLifecycle()参数
            requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode());
            current.setRequestManager(requestManager);
        }
        return requestManager;
    }
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //通过FragmentManager获取SupportRequestManagerFragment对象
    SupportRequestManagerFragment getSupportRequestManagerFragment(final FragmentManager fm) {
        SupportRequestManagerFragment current = 
            (SupportRequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
        if (current == null) {
            current = pendingSupportRequestManagerFragments.get(fm);
            if (current == null) {
                current = new SupportRequestManagerFragment();
                //这是一个HashMap,用来起缓存作用
                pendingSupportRequestManagerFragments.put(fm, current);
                //commit到外部的Activity中去
                //注意是此时fragment的生命周期就和外部Activity的生命周期绑定了
                fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
                handler.obtainMessage(ID_REMOVE_SUPPORT_FRAGMENT_MANAGER, fm).sendToTarget();
            }
        }
        return current;
    }
}

SupportRequestManagerFragment的实现

public class SupportRequestManagerFragment extends Fragment {

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //保存了一个RequestManager
    private RequestManager requestManager;
    //很明显lifecycle是和生命周期有关,
    private final ActivityFragmentLifecycle lifecycle;
    
    public SupportRequestManagerFragment() {
        this(new ActivityFragmentLifecycle());
    }
    
    public SupportRequestManagerFragment(ActivityFragmentLifecycle lifecycle) {
        this.lifecycle = lifecycle;
    }

    public void setRequestManager(RequestManager requestManager) {
        this.requestManager = requestManager;
    }
 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    @Override
    public void onStart() {
        super.onStart();
        lifecycle.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
        lifecycle.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        lifecycle.onDestroy();
    }
}

ActivityFragmentLifecycle的实现

class ActivityFragmentLifecycle implements Lifecycle {

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //LifecycleListener的集合,只有onStart(),onStop(),onDestroy()三个方法
    private final Set lifecycleListeners =
            Collections.newSetFromMap(new WeakHashMap());
            
    private boolean isStarted;
    private boolean isDestroyed;

    //Lifecycle只有这一个需要实现的接口
    @Override
    public void addListener(LifecycleListener listener) {
        lifecycleListeners.add(listener);

        if (isDestroyed) {
            listener.onDestroy();
        } else if (isStarted) {
            listener.onStart();
        } else {
            listener.onStop();
        }
    }

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //这里做的事显而易见
    void onStart() {
        isStarted = true;
        for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
            lifecycleListener.onStart();
        }
    }

    void onStop() {
        isStarted = false;
        for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
            lifecycleListener.onStop();
        }
    }

    void onDestroy() {
        isDestroyed = true;
        for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
            lifecycleListener.onDestroy();
        }
    }
}

RequestManager的实现

public class RequestManager implements LifecycleListener {

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //在创建RequestManager的同时也创建了一个RequestTracker
    private final RequestTracker requestTracker;

    public RequestManager(Context context, Lifecycle lifecycle, RequestManagerTreeNode treeNode) {
        this(context, lifecycle, treeNode, new RequestTracker(), new ConnectivityMonitorFactory());
    }

    //构造方法中的lifecycle就是SupportRequestManagerFragment的lifecycle
    RequestManager(Context context, final Lifecycle lifecycle, RequestManagerTreeNode treeNode,
            RequestTracker requestTracker, ConnectivityMonitorFactory factory) {
            
            this.requestTracker = requestTracker;
            //这个过程就是将RequestManager和SupportRequestManagerFragment生命周期绑定在一起
            lifecycle.addListener(this);
    }
    
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    @Override
    public void onStart() {
        requestTracker.resumeRequests();
    }
    
    @Override
    public void onStop() {
        requestTracker.pauseRequests();
    }
    
    @Override
    public void onDestroy() {
        requestTracker.clearRequests();
    }

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  
  //load过程开始的地方
  public DrawableTypeRequest load(String string) {
    return (DrawableTypeRequest) fromString().load(string);
  }  
  
  public DrawableTypeRequest fromString() {
    return loadGeneric(String.class);
  }
  
  private  DrawableTypeRequest loadGeneric(Class modelClass) {
        //重点关注这两个ModelLoader对象
        //将String转换为数据流 -> StreamStringLoader
        ModelLoader streamModelLoader = 
                        Glide.buildStreamModelLoader(modelClass, context);
        //将String转换为文件类型 -> FileDescriptorStringLoader 
        ModelLoader fileDescriptorModelLoader =
                        Glide.buildFileDescriptorModelLoader(modelClass, context);
                        
        //两个modelLoader以及requestTracker都被封装到DrawableTypeRequest对象中
        return optionsApplier.apply(
                new DrawableTypeRequest(modelClass, 
                streamModelLoader, 
                fileDescriptorModelLoader, 
                context, glide, requestTracker, lifecycle, optionsApplier));
    }
}

RequestTracker的实现


public class RequestTracker {
    
    private final Set requests = Collections.newSetFromMap(new WeakHashMap());
   
    @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
    private final List pendingRequests = new ArrayList();

    private boolean isPaused;

    //这里就是执行请求的地方
    public void runRequest(Request request) {
        requests.add(request);
        if (!isPaused) {
            request.begin();
        } else {
            pendingRequests.add(request);
        }
    }
    
    public void removeRequest(Request request) {
        requests.remove(request);
        pendingRequests.remove(request);
    }

    public boolean isPaused() {
        return isPaused;
    }

    public void pauseRequests() {
        isPaused = true;
        for (Request request : Util.getSnapshot(requests)) {
            if (request.isRunning()) {
                request.pause();
                pendingRequests.add(request);
            }
        }
    }

    public void resumeRequests() {
        isPaused = false;
        for (Request request : Util.getSnapshot(requests)) {
            if (!request.isComplete() && !request.isCancelled() && !request.isRunning()) {
                request.begin();
            }
        }
        pendingRequests.clear();
    }

    public void clearRequests() {
        for (Request request : Util.getSnapshot(requests)) {
            request.clear();
        }
        pendingRequests.clear();
    }

    public void restartRequests() {
        for (Request request : Util.getSnapshot(requests)) {
            if (!request.isComplete() && !request.isCancelled()) {
                // Ensure the request will be restarted in onResume.
                request.pause();
                if (!isPaused) {
                    request.begin();
                } else {
                    pendingRequests.add(request);
                }
            }
        }
    }
}

load()过程

ModelLoader接口

//一个工厂接口模型,将任意复杂的数据模型转化为一个具体的数据类型可以被DataFatcher使用
//T:原始。  Y:转化后。
//两个目的
//1、将一个具体的model转换为可以被解码为资源的数据类型
//2、允许一个model结合View的尺寸大小去获取具体的资源
public interface ModelLoader {
    DataFetcher getResourceFetcher(T model, int width, int height);
}

DataFetcher接口

public interface DataFetcher {
    //很明显是用来加载数据的
    T loadData(Priority priority) throws Exception;
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //不用关注
    void cleanup();
    String getId();
    void cancel();
}

DrawableTypeRequest实现

//是一个建造者的类,用来创建请求
//有多重继承关系,为了简洁将父类方法的实现直接写到下面类中
public class DrawableTypeRequest 
                extends DrawableRequestBuilder 
                implements DownloadOptions {
    //例如几个常用参数          
    private Drawable placeholderDrawable;
    private Drawable errorPlaceholder;
    private Priority priority = null;
    private boolean isCacheable = true;
    
    //就是很简单的把参数传进去
    //可以看出这是一个建造者类,也就是说可以在里面设置很多参数
    public GenericRequestBuilder load(ModelType model) {
        this.model = model;
        isModelSet = true;
        return this;
    }
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //into()开始的地方,最复杂的过程从这里开始
    public Target into(ImageView view) {
        //先去看看buildImageViewTarget()做了些什么
        return into(glide.buildImageViewTarget(view, transcodeClass));
    }
    
    public > Y into(Y target) {
    
        Request previous = target.getRequest();
        //如果之前有Request就删掉
        if (previous != null) {
            previous.clear();
            requestTracker.removeRequest(previous);
            previous.recycle();
        }
        //创建Request
        Request request = buildRequest(target);
        //将Request放到包装类中去
        target.setRequest(request);
        //这个更有意思,也很奇怪,为什么呢???????????????
        //这个lifecycle也就是最最上面的那个Fragment中的lifecycle,其实就是个集合
        lifecycle.addListener(target);
        //开始执行这个Resquest
        requestTracker.runRequest(request);
    
        return target;
    }
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //创建Request
    private Request buildRequest(Target target) {
        if (priority == null) {
            priority = Priority.NORMAL;
        }
        return buildRequestRecursive(target, null);
    }
    
    private Request buildRequestRecursive(Target target, ThumbnailRequestCoordinator parentCoordinator) {
        //虽然这里进行了很多操作,但是最后还是调用obtainRequest去创建Request
       return obtainRequest(target, sizeMultiplier, priority, parentCoordinator);
    }
    
    //这个有点意思,居然传入了这么多参数,而最后真的返回了一个Request
    //没错,这里就是建造者模式建造的过程,这些就是我们当时设置的参数
    //这个时候,我们当然要去看看GenericRequest的实现,具体在下面
    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);
    }


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
DrawableTypeRequest(Class modelClass, ModelLoader streamModelLoader,
            ModelLoader fileDescriptorModelLoader, Context context, Glide glide,
            RequestTracker requestTracker, Lifecycle lifecycle, RequestManager.OptionsApplier optionsApplier) {
        super(context, modelClass,
                    //注意这里生成了一个LoadProvider
                buildProvider(glide, streamModelLoader, fileDescriptorModelLoader, GifBitmapWrapper.class, GlideDrawable.class, null),
                glide, requestTracker, lifecycle);
        this.streamModelLoader = streamModelLoader;
        this.fileDescriptorModelLoader = fileDescriptorModelLoader;
        this.optionsApplier = optionsApplier;
    }
}

into()过程

GlideDrawableImageViewTarget的实现

//为了简洁,将父类的属性、方法直接放到子类中
//这类最后是实现了lifecycle的接口
public class GlideDrawableImageViewTarget extends ImageViewTarget {
    
    //这个类,很明显和Drawable有关系,很可能就是就是我们最后所需要的图片资源
    private GlideDrawable resource;
    //这个属性存储着目标的ImageView
    protected final T view;
    //这里还封装了request请求,这就有点意思了
    private Request request;

    public GlideDrawableImageViewTarget(ImageView view) {
        this(view, GlideDrawable.LOOP_FOREVER);
    }

    public GlideDrawableImageViewTarget(ImageView view, int maxLoopCount) {
        super(view);
    }
    
    public ImageViewTarget(ImageView view) {
        super(view);
    }
    
    public ViewTarget(T view) {
        if (view == null) {
            throw new NullPointerException("View must not be null!");
        }
        this.view = view;
    }
}

GenericRequest的实现

//1.既然是final修饰,也就是说这就是Request的实现了,不会有其他类继承它,再做一下骚操作
//2.需要注意这两个接口SizeReadyCallback,ResourceCallback,会有大用
public final class GenericRequest implements Request, 
    SizeReadyCallback,ResourceCallback {

    //请求开始的地方
    @Override
    public void begin() {
        //省略一些代码
        onSizeReady(overrideWidth, overrideHeight);
    }
    
    @Override
    public void onSizeReady(int width, int height) {
        
        status = Status.RUNNING;

        width = Math.round(sizeMultiplier * width);
        height = Math.round(sizeMultiplier * height);

        ModelLoader modelLoader = loadProvider.getModelLoader();
        final DataFetcher dataFetcher = modelLoader.getResourceFetcher(model, width, height);

        loadedFromMemoryCache = true;
        loadStatus = engine.load(signature, width, height, 
        dataFetcher, loadProvider, transformation, transcoder,
                priority, isMemoryCacheable, diskCacheStrategy, this);
    }
    
    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)) {
            //这个target就是ImageView生成的包装类
            //在onResourceReady()中就是把图片资源set到ImageView中去
            target.onResourceReady(result, animation);
        }

    }   

}

Engine的实现

public class Engine implements EngineJobListener,
        MemoryCache.ResourceRemovedListener,
        EngineResource.ResourceListener {
        
    public  LoadStatus load(Key signature, int width, int height, DataFetcher fetcher,
            DataLoadProvider loadProvider, Transformation transformation, ResourceTranscoder transcoder,
            Priority priority, boolean isMemoryCacheable, DiskCacheStrategy diskCacheStrategy, ResourceCallback cb) {
       

        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 engineJob = engineJobFactory.build(key, isMemoryCacheable);
        //DecodeJob: 负责解码资源和申请转码的类。
        DecodeJob decodeJob = new DecodeJob(key, 
                    width, height, fetcher, loadProvider, transformation,
                transcoder, diskCacheProvider, diskCacheStrategy, priority);
        //注意,在这里engineJob和decodeJob都被传进去了
        EngineRunnable runnable = new EngineRunnable(engineJob, decodeJob, priority);
        jobs.put(key, engineJob);
        engineJob.addCallback(cb);
        engineJob.start(runnable);

        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Started new load", startTime, key);
        }
        return new LoadStatus(cb, engineJob);
    }
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //图片资源获取、缓存、解码之后的回调
    @Override
    public void onResourceReady(final Resource resource) {
        this.resource = resource;
        MAIN_THREAD_HANDLER.obtainMessage(MSG_COMPLETE, this).sendToTarget();
    }
    
    private void handleResultOnMainThread() {
        engineResource = engineResourceFactory.build(resource, isCacheable);
        hasResource = true;
        //资源引用数
        engineResource.acquire();
        listener.onEngineJobComplete(key, engineResource);

        for (ResourceCallback cb : cbs) {
            if (!isInIgnoredCallbacks(cb)) {
                engineResource.acquire();
                cb.onResourceReady(engineResource);
            }
        }
        //释放资源
        engineResource.release();
    }
}

EngineRunnable的实现

class EngineRunnable implements Runnable, Prioritized {
    
    private final DecodeJob decodeJob;

    @Override
    public void run() {
        //从这里开始就已经在子线程工作了
        Exception exception = null;
        Resource resource = null;
        //这个resource就是最后解码得到的结果
        resource = decode();
        //这里是处理结果的步骤
        if (resource == null) {
            onLoadFailed(exception);
        } else {
            onLoadComplete(resource);
        }
    }
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    private Resource decode() throws Exception {
        if (isDecodingFromCache()) {
            //从缓存中读取,这里的缓存指的是磁盘的缓存
            return decodeFromCache();
        } else {
            //从源地址读取
            return decodeFromSource();
        }
    }
    
    //从源地址读取
    private Resource decodeFromSource() throws Exception {
        return decodeJob.decodeFromSource();
    }

}

DecodeJob的实现

class DecodeJob {

    public Resource decodeFromSource() throws Exception {
    
        Resource decoded = decodeSource();
        
        return transformEncodeAndTranscode(decoded);
    }
    
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    private Resource decodeSource() throws Exception {
        Resource decoded = null;
        //读取数据,这里已经进行了网路请求,拿到了数据
        //具体实现暂时不关注
        //这个fetcher早就在之前创建好了,一步步传递过来的
        final A data = fetcher.loadData(priority);
        decoded = decodeFromSourceData(data);
        return decoded;
    }

    private Resource decodeFromSourceData(A data) throws IOException {
        final Resource decoded;
        //省略了相当一部分代码
        decoded = cacheAndDecodeSourceData(data);
        return decoded;
    }
    
    //在这里通过key保存到了磁盘中
    private Resource cacheAndDecodeSourceData(A data) throws IOException {
        SourceWriter writer = new SourceWriter(loadProvider.getSourceEncoder(), data);
        diskCacheProvider.getDiskCache().put(resultKey.getOriginalKey(), writer);
        Resource result = loadFromCache(resultKey.getOriginalKey());
        return result;
    }  
    
    private Resource loadFromCache(Key key) throws IOException {
        File cacheFile = diskCacheProvider.getDiskCache().get(key);
        if (cacheFile == null) {
            return null;
        }

        Resource result = null;
        try {
            result = loadProvider.getCacheDecoder().decode(cacheFile, width, height);
        } finally {
            if (result == null) {
                diskCacheProvider.getDiskCache().delete(key);
            }
        }
        return result;
    } 
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    
}

缓存机制

生成缓存的key

//传入这么多参数,其实最后是重写了equals()和HashCode
//对于Url来说id就默认是当前的url
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);
    return null;
}
EngineResource active = loadFromActiveResources(key, isMemoryCacheable);
if (active != null) {
    cb.onResourceReady(active);
    return null;
}

内存缓存

1、LruCache算法(Least Recently Used)
2、弱引用机制

通过两个方法来获得内存缓存

  • loadFromCache ------LruCache算法
  • loadFromActiveSource------弱引用
//看一看LoadFromCache的执行过程
private EngineResource loadFromCache(Key key, boolean isMemoryCacheable) {
    if (!isMemoryCacheable) {
        return null;
    }
    EngineResource cached = getEngineResourceFromCache(key);
    if (cached != null) {
        //这个方法就是++操作,表示这个资源被引用数
        cached.acquire();
        activeResources.put(key, new ResourceWeakReference(key, cached, getReferenceQueue()));
    }
    return cached;
}

@SuppressWarnings("unchecked")
private EngineResource getEngineResourceFromCache(Key key) {
    //这个cache就是实现了LruCache算法
    Resource cached = cache.remove(key);
    final EngineResource result;
    if (cached == null) {
        result = null;
    } else if (cached instanceof EngineResource) {
        result = (EngineResource) cached;
    } else {
        result = new EngineResource(cached, true /*isCacheable*/);
    }
    return result;
}
//通过弱引用获取资源,
private EngineResource loadFromActiveResources(Key key, boolean isMemoryCacheable) {
    if (!isMemoryCacheable) {
        return null;
    }
    EngineResource active = null;
    //activeResources就是一个HashMap,value就是对资源的弱引用
    WeakReference> activeRef = activeResources.get(key);
    if (activeRef != null) {
        active = activeRef.get();
        if (active != null) {
            //这个方法就是++操作,表示这个资源被引用数
            //同时,对应的release()方法就是做了--操作
            active.acquire();
        } else {
            activeResources.remove(key);
        }
    }
    return active;
}

磁盘缓存

也采用LruCache策略,Glide自己实现的DiskLruCache

//这个已经是在子线程的Runnable中
private Resource decode() throws Exception {
    if (isDecodingFromCache()) {
        return decodeFromCache();
    } else {
        return decodeFromSource();
    }
}

private Resource decodeFromCache() throws Exception {
    Resource result = null
    result = decodeJob.decodeResultFromCache();
    if (result == null) {
        result = decodeJob.decodeSourceFromCache();
    }
    return result;
}

public Resource decodeResultFromCache() throws Exception {
    if (!diskCacheStrategy.cacheResult()) {
        return null;
    }
    Resource transformed = loadFromCache(resultKey);
    Resource result = transcode(transformed);
    return result;
}

public Resource decodeSourceFromCache() throws Exception {
    if (!diskCacheStrategy.cacheSource()) {
        return null;
    }
    Resource decoded = loadFromCache(resultKey.getOriginalKey())
    return transformEncodeAndTranscode(decoded);
}

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

private Resource loadFromCache(Key key) throws IOException {
    File cacheFile = diskCacheProvider.getDiskCache().get(key);
    if (cacheFile == null) {
        return null;
    }
    Resource result = null;
    try {
        result = loadProvider.getCacheDecoder().decode(cacheFile, width, height);
    } finally {
        if (result == null) {
            diskCacheProvider.getDiskCache().delete(key);
        }
    }
    return result;
}

你可能感兴趣的:(Gilde源码分析)