Android Glide: How to download and cache bitmaps?

别来无恙 提交于 2019-11-29 02:00:54

Loads in Glide don't start until you make a call to into. The RequestListener interface observes requests, but isn't typically meant for handling results. Instead of using RequestListener, consider having your callback implement the Target interface and pass it in using into.

Alternatively you could just extend SimpleTarget and pass it in to each request in the same way you're trying to use RequestListener:

Target target = Glide.with(context)
     ...
     .into(new SimpleTarget<Bitmap>(width, height) {
          @Override
          public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
              callback.onDone(resource);
          }

          @Override
          public void onLoadFailed(Exception e, Drawable errorDrawable) {
              callback.onDone(null);
          }
     });

// At some point later, if you want to cancel the load:
Glide.clear(target);

You will want to provide a width and a height so that Glide can downsample and transform images appropriately. You may also run in to issues with cancellation if you're displaying these Bitmaps in views, in which case I'd strongly recommend making the view available to your loading API and passing the view to into which will handle sizing and cancellation for you.

I use Glide 3.7.0 and download images this way:
it is important to note - it executes asyncroniously

Glide.with(this)
    .load(url)
    .downloadOnly(new SimpleTarget<File>() {
        @Override
        public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
            LOGGER.debug("Photo downloaded");
        }
    });

When I need to show cached image, I use the same url and DiskCacheStrategy.SOURCE:

Glide.with(this)
    .load(url)
    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
    .into(imageView);

It is now even simpler on Glide 4.9.0.

Glide.with(this)
    .downloadOnly()
    .load(url)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!