Glide 源码分析

此篇文章分析的是glide 3.7 版本

简单使用

    Glide.with(context)
         .load(url)
         .into(imageView);

源码实现思路

  1. with() : Glide.with(activity) 返回一个 RequestManager 类 , 并且建议这里的上下午传递activity或是fragment , glide这样会监控你生命周期 , 做优化暂停加载与恢复; RequestManager 是一个处理glide加载图片生命周期和load图片的类;

  2. load() : 使用RequestManager 调用load方法 , 最后会返回GenericRequestBuilder对象 他是处理optioninto的实现逻辑 ; 因为(多态特性) 如果你没有调用asBitmap和asGif , 那么就是 默认的DrawableRequestBuilder的实例 , 否则就是BitmapRequestBuilderGifRequestBuilder; 你得到这个RequestBuilder 其实是转发类 , 真正实现类是GenericRequestBuilder;

  3. into() : 把我们所有的参数在imageView上显示出来;

    1. buildRequest() : buildRequest 会调用 GenericRequest obtain() 把我们所有传递的参数赋值 , 进行参数是初始化 , 并返回一个Request真实实例是GenericRequest , 他是给target(imageView)加载资源的类
    2. runRequest() : build参数后调用RequestTracker类的runRequest()方法把GenericRequest传进去,RequestTracker是用于跟踪加载请求 , 暂停 , 取消 , 重新开始 等功能的类; runRequest()里调用 GenericRequest 的begin()-> onSizeReady() , 然后调用 Engine的load() , Engine 是 负责 loading 资源和缓存资源的;
    3. load() : 方法会先loadFromCache()来使用 LruResourceCache(最近最少使用算法) 来获取内存缓存 , 如果获取不到再从弱引用中 loadFromActiveResources来获取内存缓存; 都获取不到就会利用dikLruCache获取磁盘缓存 , 都拿不到缓存开网络加载资源;
    4. start() : EngineJob 的start()方法 , 他会执行EngineRunnable 的 run() 来获取 Resource 资源对象 ;
    5. onResourceReady() : 会回调EngineJob类里的 onResourceReady 这个方法; 会回调 target (其实GlideDrawableImageViewTarget的实例) 的 onResourceReady 方法;
  4. setResource() : GlideDrawableImageViewTarget 里 view.setImageDrawable(resource);

glide 编码细节分析

  1. 首先是Glide.with(activity)
//根据线程的不同来调用不同的方法
public RequestManager get(FragmentActivity activity) {
        if (Util.isOnBackgroundThread()) { 
            return get(activity.getApplicationContext());
        } else {
            assertNotDestroyed(activity);
            FragmentManager fm = activity.getSupportFragmentManager();
            return supportFragmentGet(activity, fm);//获取RequestManager
        }
    }

  1. getSupportRequestManagerFragment: 往对应的activity里添加个fragment来监听生命周期,并且通过tag 和 map 来做对象的复用;
  RequestManager supportFragmentGet(Context context, FragmentManager fm) {
        SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm);
        RequestManager requestManager = current.getRequestManager();
        if (requestManager == null) {
            requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode());
            current.setRequestManager(requestManager);
        }
        return requestManager;
    }

  1. 上面 new 个 RequestManager 对象 , 在构造方法里进行 glide的初始化 和 生命周期的监听处理
    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));

        // If we're the application level request manager, we may be created on a background thread. In that case we
        // cannot risk synchronously pausing or resuming requests, so we hack around the issue by delaying adding
        // ourselves as a lifecycle listener by posting to the main thread. This should be entirely safe.
        if (Util.isOnBackgroundThread()) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    lifecycle.addListener(RequestManager.this);
                }
            });
        } else {
            lifecycle.addListener(this);
        }
        lifecycle.addListener(connectivityMonitor);
    }

  1. glide 的 单例 , GlideBuilder 的创建 和 createGlide() 的方法 返回一个 初始化好glide参数的glide对象
public static Glide get(Context context) {
        if (glide == null) {
            synchronized (Glide.class) {
                if (glide == null) {
                    Context applicationContext = context.getApplicationContext();
                    List<GlideModule> modules = new ManifestParser(applicationContext).parse();

                    GlideBuilder builder = new GlideBuilder(applicationContext);
                    for (GlideModule module : modules) {
                        module.applyOptions(applicationContext, builder);
                    }
                    glide = builder.createGlide();
                    for (GlideModule module : modules) {
                        module.registerComponents(applicationContext, glide);
                    }
                }
            }
        }

        return glide;
    }

  1. 分别判断有没有option , 没有就设置default;
    Glide createGlide() {
        if (sourceService == null) {
            final int cores = Math.max(1, Runtime.getRuntime().availableProcessors());
            sourceService = new FifoPriorityThreadPoolExecutor(cores);
        }
        if (diskCacheService == null) {
            diskCacheService = new FifoPriorityThreadPoolExecutor(1);
        }

        MemorySizeCalculator calculator = new MemorySizeCalculator(context);
        if (bitmapPool == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                int size = calculator.getBitmapPoolSize();
                bitmapPool = new LruBitmapPool(size);//**注意这里** 如果大于11 就会创建一个默认的Lru算法的bitmap缓存池
            } else {
                bitmapPool = new BitmapPoolAdapter();
            }
        }

        if (memoryCache == null) {
            memoryCache = new LruResourceCache(calculator.getMemoryCacheSize());
        }

        if (diskCacheFactory == null) {
            diskCacheFactory = new InternalCacheDiskCacheFactory(context);
        }

        if (engine == null) {
            engine = new Engine(memoryCache, diskCacheFactory, diskCacheService, sourceService);
        }

        if (decodeFormat == null) {
            decodeFormat = DecodeFormat.DEFAULT;
        }

        return new Glide(engine, memoryCache, bitmapPool, context, decodeFormat);
    }


推荐阅读更多精彩内容