Volley提供2個靜態方法:緩存
public static RequestQueue newRequestQueue(Context context) {} public static RequestQueue newRequestQueue(Context context, HttpStack stack) {}
public ImageLoader(RequestQueue queue, ImageCache imageCache) { mRequestQueue = queue; mCache = imageCache; }
public interface ImageCache { public Bitmap getBitmap(String url); public void putBitmap(String url, Bitmap bitmap); }
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); } } }
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); } }