在后台线程上的磁盘上滑动缓存图像

Glide cache image on disk on background thread

我想使用 Glide 急切地下载图像并将它们缓存在磁盘上以备将来使用。我想从后台线程调用此功能。

我已阅读 Glide's caching documentation, but it doesn't explain how to download the image without having an actual target right now. Then I found this issue 并尝试使用类似的方法,但无论我尝试什么,我都会遇到此异常:

java.lang.IllegalArgumentException: You must call this method on the main thread

那么,我如何告诉 Glide 从后台线程缓存图像?

编辑: 我真的很想在后台线程上调用 Glide 的方法。我知道我可以使用处理程序和其他方法将其卸载到 UI 线程,但这不是我要的。

我答对了吗?

private class update extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
        RequestOptions options = new RequestOptions()
        .diskCacheStrategy(DiskCacheStrategy.ALL) // Saves all image resolution
        .centerCrop()
        .priority(Priority.HIGH)
        .placeholder(R.drawable.null_image_profile)
        .error(R.drawable.null_image_profile);

    Glide.with(context).load(imageUrl)
        .apply(options);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        //finish
    }
}

You must call this method on the main thread

无论您在何处调用方法以使用 Glide 或从后台执行某些操作,运行 内部:

runOnUiThread(new Runnable() {
                @Override
                public void run() {

              // Here, use glide or do your things on UiThread

            }
        });

在主线程中使用它,然后错误应该消失。

GlideApp.with(context)
    .downloadOnly()
    .diskCacheStrategy(DiskCacheStrategy.DATA) // Cache resource before it's decoded
    .load(url)
    .submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
    .get() // Called on background thread

如果想在 缓存中加载图像以供将来在后台线程中使用 那么 Glide 具有此功能

在这里你可以如何做到这一点

 //here i passing application context so our glide tie itself with application lifecycle

FutureTarget<File> future = Glide.with(getApplicationContext()).downloadOnly().load("your_image_url").submit();

现在,如果您想检索要存储在数据库中的已保存路径,那么您可以

File file = future.get();
String path = file.getAbsolutePath();

您也可以只在一行中执行此操作,返回这样的路径字符串

String path = Glide.with(getApplicationContext()).downloadOnly().load("your_image_url").submit().get().getAbsolutePath();