Android:如何取消回收站查看图像请求

Pan*_*sal 1 android

我正在使用 recyclerView 使用 asysnc 任务显示图像。我正在从 Web 服务器获取图像。我的代码是

从我调用的 onBindViewHolder 方法

new ImageLoadTask(url, holder.imageView).execute();
Run Code Online (Sandbox Code Playgroud)

我的 ImageLoader asysnc 任务是

public class ImageLoadTask extends AsyncTask<Void, Void, Bitmap> {

        private String url;
        private ImageView imageView;
        ProgressDialog pDialog;

        public ImageLoadTask(String url, ImageView imageView) {
            this.url = url;
            this.imageView = imageView;
        }

        @Override
        protected Bitmap doInBackground(Void... params) {
            try {
                URL urlConnection = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) urlConnection
                        .openConnection();
                connection.setDoInput(true);
                connection.connect();

                InputStream input = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(input);
                return myBitmap;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            imageView.setImageBitmap(result);
        }
    }
Run Code Online (Sandbox Code Playgroud)

问题是当我在下载图像之前滚动并跳过一个或多个视图并且该视图被回收时,图像下载请求不会在那些中间视图上取消,导致在实际图像之前闪烁该/那些图像在该视图中加载。

我尝试HttpURLConnection从适配器传递并检查它是否不为空,然后disconnect如之前从onBindViewHoldermethode调用它,但它仍然发生。我正在使用

if (holder.urlConnection != null)
    {
        holder.urlConnection.disconnect();
        try {
            holder.urlConnection.getInputStream().close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        holder.urlConnection = null;
    }

    new ImageLoadTask(url, holder.imageView,holder.viewHolderActivity, holder.urlConnection).execute();
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能取消图像请求?

小智 5

在持有人中保存 ImageLoadTask 链接

    if (holder.urlConnection != null)
        {
            holder.urlConnection.disconnect();
            try {
                holder.urlConnection.getInputStream().close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            holder.urlConnection = null;
        }

      holder.imageTask = new ImageLoadTask(url, holder.imageView,holder.viewHolderActivity, holder.urlConnection);
      holder.imageTask.execute();
Run Code Online (Sandbox Code Playgroud)

并取消它

//Called when a view created by this adapter has been recycled.
public void onViewRecycled(VH holder){
      holder.imageTask.cancel();
}
Run Code Online (Sandbox Code Playgroud)