Volley提供2个静态方法:
public static RequestQueue newRequestQueue(Context context) {} public static RequestQueue newRequestQueue(Context context, HttpStack stack) {}
第一个直接调用第二个的newRequestQueue(context, null);方法,返回都是一个RequestQueue 对象
以ImageLoader为例 构造方法
public ImageLoader(RequestQueue queue, ImageCache imageCache) { mRequestQueue = queue; mCache = imageCache; }
需要一个RequestQueue 对象 和一个ImageCache对象 ,RequestQueue 可以通过Volley类中的静态方法newRequestQueue(Context context) 获得,而ImageCache 则是一个interface
public interface ImageCache { public Bitmap getBitmap(String url); public void putBitmap(String url, Bitmap bitmap); }
实现此接口,即上一文章中Cache包下的BitmapCache,赋值给mCache对象
mCache中缓存key value,key规则为String key = "#W"+maxWidth+"#H"+ maxHeight +url;
再来看下面方法
参数:defaultImageResId:未开始下载显示的图片Id,如果传递0则不显示任何东西
errorImageResId:下载显示的图片Id,如果传递0则不显示任何东西
返回值:ImageListener
public static ImageListener getImageListener(final ImageView view, final int defaultImageResId, final int errorImageResId) { ... ...//直接new一个ImageListener @Override public void onResponse(ImageContainer response, boolean isImmediate) { if (response.getBitmap() != null) { //response有值设置ImageView显示图片 view.setImageBitmap(response.getBitmap()); } else if (defaultImageResId != 0) { view.setImageResource(defaultImageResId); } } }
response.getBitmap()中的bitmap是通过BatchedImageRequest中的batchResponse(),
通过一个ImageContainer类中的Interface:ImageListerner.onResponse回调回来的
private void batchResponse(String cacheKey, BatchedImageRequest request, final VolleyError error) { mBatchedResponses.put(cacheKey, request); // If we don't already have a batch delivery runnable in flight, make a new one. // Note that this will be used to deliver responses to all callers in mBatchedResponses. if (mRunnable == null) { mRunnable = new Runnable() { @Override public void run() { for (BatchedImageRequest bir : mBatchedResponses.values()) { for (ImageContainer container : bir.mContainers) { if (container.mListener == null) { continue; } if (error == null) { //取得数据 container.mBitmap = bir.mResponseBitmap; //通过ImageContainer中的mListener,即ImageListener中的onResponse()方法回调 container.mListener.onResponse(container, false); } else { container.mListener.onErrorResponse(error); } } } mBatchedResponses.clear(); mRunnable = null; } }; // Post the runnable. mHandler.postDelayed(mRunnable, mBatchResponseDelayMs); } }