Glide加多本地图片文件缓存
2022-07-12 本文已影响0人
你的益达233
需求:想在glide的基础上再做下载到本地 如果本地有图优先取用本地的图
示例代码如下:
private static ExecutorService cachedThreadPool;
@SuppressLint("NewApi")
public static void load(Context context, ImageView imageView, String url) {
if (TextUtils.isEmpty(url)) {
return;
}
if(!((Activity)context).isFinishing() && !((Activity)context).isDestroyed()){
String beforeSaveFilePath = "";
if (PermissionAppUtils.hasPermissions(context,PermissionAppUtils.Group.STORAGE)){
String temp[] = url.replaceAll("\\\\","/").split("/");
String fileUrlName = "";
if(temp.length > 1){
fileUrlName = temp[temp.length - 1];
}
if (!fileUrlName.endsWith(".jpg")){
fileUrlName = fileUrlName+".jpg";
}
File file = new File(ToolUtils.getDownCustomerLocalPath());
File[] subFile = file.listFiles();
if (subFile != null && subFile.length > 0){
for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
// 判断是否为文件夹
if (!subFile[iFileLength].isDirectory()) {
String filename = subFile[iFileLength].getName();
if (filename.equals(fileUrlName)){
beforeSaveFilePath = subFile[iFileLength].getPath();
break;
}
}
}
}
}
if (!TextUtils.isEmpty(beforeSaveFilePath)){
loadLocalFile(context,imageView,beforeSaveFilePath);
} else {
Glide.with(context)
.asBitmap()
.load(url)
.dontAnimate()
.error(Glide.with(context)
.load(url).into(imageView))
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
if (PermissionAppUtils.hasPermissions(context,PermissionAppUtils.Group.STORAGE)){
if (cachedThreadPool == null){
cachedThreadPool = Executors.newCachedThreadPool();
}
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
String temp[] = url.replaceAll("\\\\","/").split("/");
String fileName = "";
if(temp.length > 1){
fileName = temp[temp.length - 1];
}
if (!fileName.endsWith(".jpg")){
fileName = fileName+".jpg";
}
setBitmapToLocal(context,fileName,resource);
}
});
}
imageView.setImageBitmap(resource);
}
});
}
}
}
要完整代码的可私信我