Glide图片请求:downloadOnly是否在仅下载前检查缓存?

3
我正在像下面这样发出请求,但是我想知道downloadOnly是否首先检查缓存中的图像?
FutureTarget<File> future = Glide.with(applicationContext)
    .load(yourUrl)
    .downloadOnly(500, 500);
File cacheFile = future.get();

我的主要问题是,yourUrl中的图像已经被加载到缓存中,我需要一种同步方式在后台线程中从缓存中检索图像。

上面的代码可以工作,但我需要知道是否有缓存检查在downloadOnly之前。谢谢。

1个回答

2

在为Glide打开详细日志记录后,我能够清楚地看到调用图像时发生了什么,DecodeJob大部分时间都从缓存中获取数据,不到10毫秒,但有时会再次获取数据,可能是从磁盘或网络获取。

因此,最终我使用自定义的StreamModelLoader仅检查缓存,如果尝试通过网络获取数据则抛出异常,在缓存未命中时使用默认流程。

private final StreamModelLoader<String> cacheOnlyStreamLoader = new StreamModelLoader<String>() {
        @Override
        public DataFetcher<InputStream> getResourceFetcher(final String model, int i, int i1) {
            return new DataFetcher<InputStream>() {
                @Override
                public InputStream loadData(Priority priority) throws Exception {
                    throw new IOException();
                }

                @Override
                public void cleanup() {

                }

                @Override
                public String getId() {
                    return model;
                }

                @Override
                public void cancel() {

                }
            };
        }
    };

FutureTarget<File> future = Glide.with(progressBar.getContext())
                    .using(cacheOnlyStreamLoader)
                    .load(url).downloadOnly(width, height);

            File cacheFile = null;
            try {
                cacheFile = future.get();
            } catch(Exception ex) {
                ex.printStackTrace();  //exception thrown if image not in cache
            }

            if(cacheFile == null || cacheFile.length() < 1) {
                //didn't find the image in cache
                future = Glide.with(progressBar.getContext())
                        .load(url).downloadOnly(width, height);

                cacheFile = future.get(3, TimeUnit.SECONDS); //wait 3 seconds to retrieve the image
            }

1
那么结果是什么? - Nick Cardoso

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接