Skip to content

Loading and Caching on Background Threads

Sam edited this page May 20, 2017 · 3 revisions

Glide V4

For information on Glide v4, see the documentation. This wiki covers Glide v3 only.


To make loading and interacting with media on background threads easier, Glide provides two APIs in addition to the normal Glide.with(fragment).load(url).into(view) API:

downloadOnly

Glide's downloadOnly() API allows you to download the bytes of an image into the disk cache so that it will be available to be retrieved later. You can use downloadOnly() asynchronously on the ui thread or synchronously on a background thread. Note that the arguments are slightly different, the asynchronous api takes a Target and the synchronous api takes an integer width and height.

To download images on a background thread, you must use the synchronous version:

FutureTarget<File> future = Glide.with(applicationContext)
    .load(yourUrl)
    .downloadOnly(500, 500);
File cacheFile = future.get();

Once the future returns, the bytes of the image are available in the cache. Typically the downloadOnly() API is only used to make sure the bytes are available on disk. Although you are given access to the underlying cache File, you usually don’t want to interact with it.

Instead when you later want to retrieve your image, you can do so using a normal call with one exception:

Glide.with(yourFragment)
    .load(yourUrl)
    .diskCacheStrategy(DiskCacheStrategy.ALL)
    .into(yourView);

By passing in DiskCacheStrategy.ALL or DiskCacheStrategy.SOURCE, you make sure Glide will use the bytes you cached using downloadOnly().

into

If you actually want to interact with a decoded image on a background thread, instead of using downloadOnly you can use the version of into() that returns a FutureTarget. For example, to get the center cropped bytes of a 500px by 500px image:

Bitmap myBitmap = Glide.with(applicationContext)
    .load(yourUrl)
    .asBitmap()
    .centerCrop()
    .into(500, 500)
    .get()

Although into(int, int) works well on background threads, note that you must not use it on the main thread. Even if the synchronous version of into did not throw an exception when used on the main thread, calling get() would block the main thread, reducing the performance and responsiveness of your app.

Clone this wiki locally