FileDocCategorySizeDatePackage
ImageLoader.javaAPI DocAndroid 5.1 API19172Thu Mar 12 22:22:56 GMT 2015com.android.volley.toolbox

ImageLoader

public class ImageLoader extends Object
Helper that handles loading and caching images from remote URLs. The simple way to use this class is to call {@link ImageLoader#get(String, ImageListener)} and to pass in the default image listener provided by {@link ImageLoader#getImageListener(ImageView, int, int)}. Note that all function calls to this class must be made from the main thead, and all responses will be delivered to the main thread as well.

Fields Summary
private final com.android.volley.RequestQueue
mRequestQueue
RequestQueue for dispatching ImageRequests onto.
private int
mBatchResponseDelayMs
Amount of time to wait after first response arrives before delivering all responses.
private final ImageCache
mCache
The cache implementation to be used as an L1 cache before calling into volley.
private final HashMap
mInFlightRequests
HashMap of Cache keys -> BatchedImageRequest used to track in-flight requests so that we can coalesce multiple requests to the same URL into a single network request.
private final HashMap
mBatchedResponses
HashMap of the currently pending responses (waiting to be delivered).
private final android.os.Handler
mHandler
Handler to the main thread.
private Runnable
mRunnable
Runnable for in-flight response delivery.
Constructors Summary
public ImageLoader(com.android.volley.RequestQueue queue, ImageCache imageCache)
Constructs a new ImageLoader.

param
queue The RequestQueue to use for making image requests.
param
imageCache The cache to use as an L1 cache.


                                        
       
           
             
    

                                 
         
        mRequestQueue = queue;
        mCache = imageCache;
    
Methods Summary
private voidbatchResponse(java.lang.String cacheKey, com.android.volley.toolbox.ImageLoader$BatchedImageRequest request)
Starts the runnable for batched delivery of responses if it is not already started.

param
cacheKey The cacheKey of the response being delivered.
param
request The BatchedImageRequest to be delivered.
param
error The volley error associated with the request (if applicable).

        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 one of the callers in the batched request canceled the request
                            // after the response was received but before it was delivered,
                            // skip them.
                            if (container.mListener == null) {
                                continue;
                            }
                            if (bir.getError() == null) {
                                container.mBitmap = bir.mResponseBitmap;
                                container.mListener.onResponse(container, false);
                            } else {
                                container.mListener.onErrorResponse(bir.getError());
                            }
                        }
                    }
                    mBatchedResponses.clear();
                    mRunnable = null;
                }

            };
            // Post the runnable.
            mHandler.postDelayed(mRunnable, mBatchResponseDelayMs);
        }
    
public com.android.volley.toolbox.ImageLoader$ImageContainerget(java.lang.String requestUrl, com.android.volley.toolbox.ImageLoader$ImageListener listener)
Returns an ImageContainer for the requested URL. The ImageContainer will contain either the specified default bitmap or the loaded bitmap. If the default was returned, the {@link ImageLoader} will be invoked when the request is fulfilled.

param
requestUrl The URL of the image to be loaded.
param
defaultImage Optional default image to return until the actual image is loaded.

        return get(requestUrl, listener, 0, 0);
    
public com.android.volley.toolbox.ImageLoader$ImageContainerget(java.lang.String requestUrl, com.android.volley.toolbox.ImageLoader$ImageListener imageListener, int maxWidth, int maxHeight)
Issues a bitmap request with the given URL if that image is not available in the cache, and returns a bitmap container that contains all of the data relating to the request (as well as the default image if the requested image is not available).

param
requestUrl The url of the remote image
param
imageListener The listener to call when the remote image is loaded
param
maxWidth The maximum width of the returned image.
param
maxHeight The maximum height of the returned image.
return
A container object that contains all of the properties of the request, as well as the currently available image (default if remote is not loaded).

        // only fulfill requests that were initiated from the main thread.
        throwIfNotOnMainThread();

        final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight);

        // Try to look up the request in the cache of remote images.
        Bitmap cachedBitmap = mCache.getBitmap(cacheKey);
        if (cachedBitmap != null) {
            // Return the cached bitmap.
            ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null);
            imageListener.onResponse(container, true);
            return container;
        }

        // The bitmap did not exist in the cache, fetch it!
        ImageContainer imageContainer =
                new ImageContainer(null, requestUrl, cacheKey, imageListener);

        // Update the caller to let them know that they should use the default bitmap.
        imageListener.onResponse(imageContainer, true);

        // Check to see if a request is already in-flight.
        BatchedImageRequest request = mInFlightRequests.get(cacheKey);
        if (request != null) {
            // If it is, add this request to the list of listeners.
            request.addContainer(imageContainer);
            return imageContainer;
        }

        // The request is not already in flight. Send the new request to the network and
        // track it.
        Request<?> newRequest =
            new ImageRequest(requestUrl, new Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap response) {
                    onGetImageSuccess(cacheKey, response);
                }
            }, maxWidth, maxHeight,
            Config.RGB_565, new ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    onGetImageError(cacheKey, error);
                }
            });

        mRequestQueue.add(newRequest);
        mInFlightRequests.put(cacheKey,
                new BatchedImageRequest(newRequest, imageContainer));
        return imageContainer;
    
private static java.lang.StringgetCacheKey(java.lang.String url, int maxWidth, int maxHeight)
Creates a cache key for use with the L1 cache.

param
url The URL of the request.
param
maxWidth The max-width of the output.
param
maxHeight The max-height of the output.

        return new StringBuilder(url.length() + 12).append("#W").append(maxWidth)
                .append("#H").append(maxHeight).append(url).toString();
    
public static com.android.volley.toolbox.ImageLoader$ImageListenergetImageListener(android.widget.ImageView view, int defaultImageResId, int errorImageResId)
The default implementation of ImageListener which handles basic functionality of showing a default image until the network response is received, at which point it will switch to either the actual image or the error image.

param
imageView The imageView that the listener is associated with.
param
defaultImageResId Default image resource ID to use, or 0 if it doesn't exist.
param
errorImageResId Error image resource ID to use, or 0 if it doesn't exist.

        return new ImageListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (errorImageResId != 0) {
                    view.setImageResource(errorImageResId);
                }
            }

            @Override
            public void onResponse(ImageContainer response, boolean isImmediate) {
                if (response.getBitmap() != null) {
                    view.setImageBitmap(response.getBitmap());
                } else if (defaultImageResId != 0) {
                    view.setImageResource(defaultImageResId);
                }
            }
        };
    
public booleanisCached(java.lang.String requestUrl, int maxWidth, int maxHeight)
Checks if the item is available in the cache.

param
requestUrl The url of the remote image
param
maxWidth The maximum width of the returned image.
param
maxHeight The maximum height of the returned image.
return
True if the item exists in cache, false otherwise.

        throwIfNotOnMainThread();

        String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight);
        return mCache.getBitmap(cacheKey) != null;
    
private voidonGetImageError(java.lang.String cacheKey, com.android.volley.VolleyError error)
Handler for when an image failed to load.

param
cacheKey The cache key that is associated with the image request.

        // Notify the requesters that something failed via a null result.
        // Remove this request from the list of in-flight requests.
        BatchedImageRequest request = mInFlightRequests.remove(cacheKey);

        if (request != null) {
            // Set the error for this request
            request.setError(error);

            // Send the batched response
            batchResponse(cacheKey, request);
        }
    
private voidonGetImageSuccess(java.lang.String cacheKey, android.graphics.Bitmap response)
Handler for when an image was successfully loaded.

param
cacheKey The cache key that is associated with the image request.
param
response The bitmap that was returned from the network.

        // cache the image that was fetched.
        mCache.putBitmap(cacheKey, response);

        // remove the request from the list of in-flight requests.
        BatchedImageRequest request = mInFlightRequests.remove(cacheKey);

        if (request != null) {
            // Update the response bitmap.
            request.mResponseBitmap = response;

            // Send the batched response
            batchResponse(cacheKey, request);
        }
    
public voidsetBatchedResponseDelay(int newBatchedResponseDelayMs)
Sets the amount of time to wait after the first response arrives before delivering all responses. Batching can be disabled entirely by passing in 0.

param
newBatchedResponseDelayMs The time in milliseconds to wait.

        mBatchResponseDelayMs = newBatchedResponseDelayMs;
    
private voidthrowIfNotOnMainThread()

        if (Looper.myLooper() != Looper.getMainLooper()) {
            throw new IllegalStateException("ImageLoader must be invoked from the main thread.");
        }