glide 设置缓存路径

glide下载的图片缓存都是保存到app内的,有时候可能会有需求把缓存放到SD卡上,当然,我的手机没有SD卡,所以就没法测试怎么设置SD卡路径了
按照教程在build.gradle内添加
implementation 'com.github.bumptech.glide:glide:4.5.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.5.0'
新建个类继承AppGlideModule
@GlideModule
public class GlideCache extends AppGlideModule {
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        super.applyOptions(context, builder);
    }

    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
        super.registerComponents(context, glide, registry);
    }
}
上面@GlideModule是必须要加的
然后修改applyOptions内的代码
@Override
public void applyOptions(Context context, GlideBuilder builder) {
    int diskCacheSizeBytes = 1024 * 1024 * 100; // 100 MB
    //手机app路径
    appRootPath = context.getCacheDir().getPath();
    builder.setDiskCache(
            new DiskLruCacheFactory( getStorageDirectory()+"/GlideDisk", diskCacheSizeBytes )
    );

}
//外部路径
private String sdRootPath = Environment.getExternalStorageDirectory().getPath();
private String appRootPath = null;

private String getStorageDirectory(){
    return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ?
            sdRootPath : appRootPath;
}

判断是否有外部路径,有就设置这个路径,没有就用内部路径
然后Build->Make Project,之后就可以在代码中使用GlideApp了
GlideApp.with(this).load("http://ww4.sinaimg.cn/large/610dc034gw1f96kp6faayj20u00jywg9.jpg").into(imageView);

缓存保存到了指定路径
记得加权限,网络和文件读写权限
网上有很多glide的资料,以后用到慢慢搞




猜你喜欢

转载自blog.csdn.net/u010302327/article/details/79034539