代码之家  ›  专栏  ›  技术社区  ›  Vasiliy

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

  •  3
  • Vasiliy  · 技术社区  · 7 年前

    我读过 Glide's caching documentation ,但它没有解释如何在没有实际目标的情况下下载图像。然后我发现 this issue

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

    那么,如何让Glide缓存来自背景线程的图像呢?

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

    5 回复  |  直到 7 年前
        1
  •  13
  •   veritas1    7 年前
    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
    
        2
  •  3
  •   Ashwini Violet    7 年前

    缓存以备将来在后台线程中使用 那么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();
    
        3
  •  0
  •   ʍѳђઽ૯ท    7 年前

    必须调用此方法

    无论你在哪里调用一个方法 Glide 或者在后台做些什么,跑进去:

    runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
    
                  // Here, use glide or do your things on UiThread
    
                }
            });
    

        4
  •  0
  •   Trk    7 年前

    我答对问题了吗?

    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
        }
    }