我正在开发从 Amazon S3 加载图像的 Android 应用程序。 图片 URL 随 token 和过期 key 随机变化。出于这个原因,我无法缓存图像 Glide。
有任何方法可以将 Glide 缓存键设置为任何静态 ID(如图像 ID)而不是 url。
我附加了我的代码 fragment 以从 AWS 加载图像
Glide.with(remoteGalleryAct).load(photoFinalImageURL)
.signature(new StringSignature(getImageUrl(photoFinalImageURL)))// remove AWS keys
.error(defaultNoImageDrawable)
.placeholder(defaultNoImageDrawable)
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(new ImageViewTarget<GlideDrawable>(photoHolder.photo) {
@Override
protected void setResource(GlideDrawable resource) {
}
@Override
public void onResourceReady(final GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
//super.onResourceReady(resource, glideAnimation);
view.setImageDrawable(resource);
}
});
请建议我有什么方法可以在 Glide 中实现。
最佳答案
覆盖 GlideUrl 类的 getCacheKey() 方法。此方法设置用于缓存图像的 key 。
方法如下:
//Create a custom class and override the method to remove authentication header from the S3 image url
public class GlideUrlCustomCacheKey extends GlideUrl {
public GlideUrlCustomCacheKey(String url) {
super(url);
}
public GlideUrlCustomCacheKey(String url, Headers headers) {
super(url, headers);
}
public GlideUrlCustomCacheKey(URL url) {
super(url);
}
public GlideUrlCustomCacheKey(URL url, Headers headers) {
super(url, headers);
}
@Override
public String getCacheKey() {
String url = toStringUrl();
if (url.contains("?")) {
return url.substring(0, url.lastIndexOf("?"));
} else {
return url;
}
}
}
使用从此类获取的 URL 设置 imageView:
Glide.with(context).load(new GlideUrlCustomCacheKey(buzzUrl)).into(imageView);
关于android - 使用 id 不是 url 的 Glide 图像缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40550729/