Android App架构

跟着源码学设计:Glide框架及源码解析(三)

2017-10-20  本文已影响51人  肖丹晨

前言

近期研究了一下Glide的图片加载框架,在这里和大家分享一下。由于代码研读有限,难免有错误的地方,了解的童鞋还望指正。学习小组QQ群: 193765960。

本篇是Glide框架及源码解析的第三篇,更多文章敬请关注后续文章。如果这篇文章对大家学习Glide有帮助,还望大家多多转载。

版权归作者所有,如有转发,请注明文章出处:http://www.jianshu.com/u/d43d948bef39

相关文章:

跟着源码学设计:Glide框架及源码解析(一)
跟着源码学设计:Glide框架及源码解析(二)
跟着源码学设计:Glide框架及源码解析(三)
跟着源码学设计:Glide框架及源码解析(四)
跟着源码学设计:Glide框架及源码解析(五)

Glide内存缓存机制

在之前的两篇中我们剖析了Glide的生命周期绑定机制和Glide的请求管理机制。接下来按说应该讲到request实际请求资源并回调刷新界面这一块了,但是为了更好的理解Glide在这一块的设计,我先大致的讲一讲Glide的内存缓存和管理机制。
不同于其他常见网络加载框架只有LruCatch一种缓存机制,Glide内存为三块(非常牛逼巧妙的设计):

注意:

说的比较抽象,是不是懵逼了?别急,上图:


Glide内存缓存及管理机制

这样就完成了一个资源的完整的循环。

BitmapPool的内存复用机制

知识储备:

使用inbitmap前,内存占用情况

使用inbitmap前,内存占用情况

使用inbitmap后,内存占用情况

使用inbitmap后,内存占用情况

下面看一下核心代码:Downsampler的downsampleWithSize()方法

private Bitmap downsampleWithSize(MarkEnforcingInputStream is, RecyclableBufferedInputStream  bufferedStream,
BitmapFactory.Options options, BitmapPool pool, int inWidth, int inHeight, int sampleSize,
DecodeFormat decodeFormat) {
  // Prior to KitKat, the inBitmap size must exactly match the size of the bitmap we're decoding.
  Bitmap.Config config = getConfig(is, decodeFormat);
  options.inSampleSize = sampleSize;
  options.inPreferredConfig = config;
  if ((options.inSampleSize == 1 || Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) && shouldUsePool(is)) {
    int targetWidth = (int) Math.ceil(inWidth / (double) sampleSize);
    int targetHeight = (int) Math.ceil(inHeight / (double) sampleSize);
    // BitmapFactory will clear out the Bitmap before writing to it, so getDirty is safe.
    setInBitmap(options, pool.getDirty(targetWidth, targetHeight, config));
  }
  return decodeStream(is, bufferedStream, options);
}
 
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static void setInBitmap(BitmapFactory.Options options, Bitmap recycled) {
  if (Build.VERSION_CODES.HONEYCOMB <= Build.VERSION.SDK_INT) {
    options.inBitmap = recycled;
  }
}

让我们先看一下我们最常见到的LruMemoryCache机制

ActiveResourceCache的设计

让我们再来看一下Glide的机制

ActiveResourceCache的设计

(本篇是Glide框架及源码解析的第三篇,更多文章敬请关注后续文章。版权归作者所有,如有转发,请注明文章出处:原文链接

上一篇下一篇

猜你喜欢

热点阅读