ublic class CanvasImageTask extends AsyncTask<ImageView, Void, Bitmap>{ private ImageView gView ; protected Bitmap doInBackground(ImageView... views) { Bitmap bmp = null ; ImageView view = views[0]; // 根据iconUrl获取图片并渲染,iconUrl的url放在了view的tag中。 if (view.getTag() != null) { try { URL url = new URL(view.getTag().toString()); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.connect(); InputStream stream = conn.getInputStream(); bmp = BitmapFactory.decodeStream(stream); stream.close(); } catch (Exception e) { Log.v("img", e.getMessage()); return null; } } this.gView = view; return bmp; } protected void onPostExecute(Bitmap bm) { if (bm != null) { this.gView.setImageBitmap(bm); this.gView = null ; } } } 在Activity中直接调用 if(!img.isDrawingCacheEnabled() || !holder.image.getTag().equals(imgpath)){ img.setImageResource(R.drawable.icon_app); img.setTag(imgpath); try{ new CanvasImageTask().execute(img); img.setDrawingCacheEnabled(true); }catch (Exception e) { Log.e("error", "RejectedExecutionException in content_img: " + imgpath);
这样图片加载使用异步线程便不会进行堵塞发生错误,我们还可以使用 callback 在图片加载完后进行回调