Glide

Glide是一个快速高效的Android图片加载库,注重于列表滚动


使用

1、添加依赖:

implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'

2、添加网络权限

<uses-permission android:name="android.permission.INTERNET" />

3、一句代码加载图片到ImageView
1
2
3
4
5
6
7
8
9
10
11
12
13
Glide.with(this).load(imgUrl).into(mIv1);

//进阶
RequestOptions options = new RequestOptions()
.placeholder(R.drawable.ic_launcher_background)
.error(R.mipmap.ic_launcher)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.override(200, 100);//override指定加载图片大小

Glide.with(this)
.load(imgUrl)
.apply(options)
.into(mIv2);

缓存

LRUCache和DiskLRUCache内部都是用了LinkedHashMap

LinkedHashMap继承于HashMap,底层基于HashMap和双向链表来实现的。

onLowMemory

当内存不足的时候,Activity、Fragment会调用onLowMemory方法,可以在这个方法里去清除缓存,Glide使用的就是这一种方式来防止OOM。

1
2
3
4
5
6
7
8
9
10
11
//Glide
public void onLowMemory() {
clearMemory();
}

public void clearMemory() {
Util.assertMainThread();
memoryCache.clearMemory();
bitmapPool.clearMemory();
arrayPool.clearMemory();
}

Bitmap像素存储位置

  • 3.0-4.0+ native heap
  • 5.0-7.0+ java heap
  • 8.0+ native heap (数据在native heap,通过jni在java层创建对象,在java heap)

Glide缓存原理

发起请求

|Start|

ActiveResources —|Yes|—> 完成

|No|

MemoryCache —|Yes|—> 完成后,缓存至ActiveResources

|No|

DiskCache —|Yes|—> 完成后,缓存至MemoryCache

|No|

网络 -> 完成后,缓存至DiskCache

activeEngineResources 是弱引用缓存, 会首先从弱引用缓存中查找, 如果找到engineResources引用数加一, 如果没有找到就去lrucache中查找, 查找到就从lrucache中移除并添加到activeEngineResources中, 如果engineResources的应用数为零的时候, 会将engineResources 从activeEngineResources中移除, 并添加到lrucache中;

如果从activeEngineResources 和lrucache中都没有找到, 就去dislrucache中查找(如果设置使用dislrucache, 如果没有设置就去下载图片);

当图片加载完成之后,会在EngineJob当中通过Handler发送一条消息将执行逻辑切回到主线程当中,从而执行handleResultOnMainThread()方法。

最后engineResource 通过activeResources.activate(key, resource) 保存到activeEngineResources中, 然后通过acquire()增加引用数,通过release()减少引用数, 当引用数为零时移除activeEngineResources, 并添加到lrucache中;