* It requires the INTERNET permission, which should be added to your * application's manifest file. *
* * A local cache of downloaded images is maintained internally to improve * performance. */ class ImageDownloader { private static final String LOG_TAG = ImageDownloader.class.getSimpleName(); private BitmapDownloaderTask task; /** * Download the specified image from the Internet and binds it to the * provided ImageView. The binding is immediate if the image is found in the * cache and will be done asynchronously otherwise. A null bitmap will be * associated to the ImageView if an error occurs. * * @param url * The URL of the image to download. * @param imageView * The ImageView to bind the downloaded image to. */ public void download(String url, ImageView imageView) { resetPurgeTimer(); Bitmap bitmap = getBitmapFromCache(url); if (bitmap == null) { forceDownload(url, imageView); } else { cancelPotentialDownload(url, imageView); imageView.setImageBitmap(bitmap); } } /* * Same as download but the image is always downloaded and the cache is not * used. Kept private at the moment as its interest is not clear. private * void forceDownload(String url, ImageView view) { forceDownload(url, view, * null); } */ /** * Same as download but the image is always downloaded and the cache is not * used. Kept private at the moment as its interest is not clear. */ private void forceDownload(String url, ImageView imageView) { // State sanity: url is guaranteed to never be null in // DownloadedDrawable and cache keys. if (url == null) { imageView.setImageDrawable(null); return; } if (cancelPotentialDownload(url, imageView)) { task = new BitmapDownloaderTask(imageView); DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task); imageView.setImageDrawable(downloadedDrawable); task.execute(url); } } /** * Returns true if the current download has been canceled or if there was no * download in progress on this image view. Returns false if the download in * progress deals with the same url. The download is not stopped in that * case. */ private static boolean cancelPotentialDownload(String url, ImageView imageView) { BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView); if (bitmapDownloaderTask != null) { String bitmapUrl = bitmapDownloaderTask.url; if ((bitmapUrl == null) || (!bitmapUrl.equals(url))) { bitmapDownloaderTask.cancel(true); } else { // The same URL is already being downloaded. return false; } } return true; } /** * @param imageView * Any imageView * @return Retrieve the currently active download task (if any) associated * with this imageView. null if there is no such task. */ private static BitmapDownloaderTask getBitmapDownloaderTask( ImageView imageView) { if (imageView != null) { Drawable drawable = imageView.getDrawable(); if (drawable instanceof DownloadedDrawable) { DownloadedDrawable downloadedDrawable = (DownloadedDrawable) drawable; return downloadedDrawable.getBitmapDownloaderTask(); } } return null; } Bitmap downloadBitmap(String url) { final int IO_BUFFER_SIZE = 4 * 1024; // AndroidHttpClient is not allowed to be used from the main thread final HttpClient client = new DefaultHttpClient(); final HttpGet getRequest = new HttpGet(url); try { HttpResponse response = client.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); return null; } else Log.d("ImageDownloader", "Success " + statusCode + " while retrieving bitmap from " + url); final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { inputStream = entity.getContent(); // return BitmapFactory.decodeStream(inputStream); // Bug on slow connections, fixed in future release. return BitmapFactory.decodeStream(new FlushedInputStream( inputStream)); } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } catch (IOException e) { getRequest.abort(); Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e); } catch (IllegalStateException e) { getRequest.abort(); Log.w(LOG_TAG, "Incorrect URL: " + url); } catch (Exception e) { getRequest.abort(); Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e); } return null; } /* * An InputStream that skips the exact number of bytes provided, unless it * reaches EOF. */ static class FlushedInputStream extends FilterInputStream { public FlushedInputStream(InputStream inputStream) { super(inputStream); } @Override public long skip(long n) throws IOException { long totalBytesSkipped = 0L; while (totalBytesSkipped < n) { long bytesSkipped = in.skip(n - totalBytesSkipped); if (bytesSkipped == 0L) { int b = read(); if (b < 0) { break; // we reached EOF } else { bytesSkipped = 1; // we read one byte } } totalBytesSkipped += bytesSkipped; } return totalBytesSkipped; } } /** * The actual AsyncTask that will asynchronously download the image. */ class BitmapDownloaderTask extends AsyncTask* Contains a reference to the actual download task, so that a download task * can be stopped if a new binding is required, and makes sure that only the * last started download process can bind its result, independently of the * download finish order. *
*/ static class DownloadedDrawable extends ColorDrawable { private final WeakReference