ImageDownloader

本文介绍了一个用于异步图片加载的类ImageDownloader,该类支持从互联网下载图片并缓存,以提高应用性能。通过使用软引用和弱引用管理缓存,确保在内存紧张时能有效释放资源,同时提供了下载失败时的默认处理机制。

用于异步图片加载:

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;

/**
 * This helper class download images from the Internet and binds those with the provided ImageView.
 *
 * <p>It requires the INTERNET permission, which should be added to your application's manifest
 * file.</p>
 *
 * A local cache of downloaded images is maintained internally to improve performance.
 */
public class ImageDownloader {
    private static final String TAG = ImageDownloader.class.getSimpleName();
    private Drawable mDefaultDrawable = null;
    private static ImageDownloader instance = null;
    private ImageDownloader(){}
    public static ImageDownloader getInstance(){
		if(instance == null){
			instance = new ImageDownloader();
			
		}
		return instance;
	}
    //public enum Mode { NO_ASYNC_TASK, NO_DOWNLOADED_DRAWABLE, CORRECT }
   // private Mode mode = Mode.NO_ASYNC_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.
     * @param defaultDrawable Show the Drawable for the ImageView when downloaded fail.
     */
    public void download(String url, ImageView imageView, Drawable defaultDrawable) {
    	setImageDefault(imageView, defaultDrawable);
    	if (url == null) {
			return;
		}
        resetPurgeTimer();
        Bitmap bitmap = getBitmapFromCache(url);
        /*Log.w(TAG, "URL ====" + url);
        Log.w(TAG, "bitmap ====" + bitmap);*/
        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)) {
           
        	 BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
             DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
             imageView.setImageDrawable(downloadedDrawable);
             imageView.setMinimumHeight(5);//TODO:
             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() ;
           // AndroidHttpClient.newInstance("Android");
        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(TAG, "Error " + statusCode + " while retrieving bitmap from " + url);
                return null;
            }

            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(TAG, "I/O error while retrieving bitmap from " + url, e);
        } catch (IllegalStateException e) {
            getRequest.abort();
            Log.w(TAG, "Incorrect URL: " + url);
        } catch (Exception e) {
            getRequest.abort();
            Log.w(TAG, "Error while retrieving bitmap from " + url, e);
        } finally {
            /*if ((client instanceof AndroidHttpClient)) {
                ((AndroidHttpClient) client).close();
            }*/
        	if (client != null && client.getConnectionManager() != null) {
				client.getConnectionManager().shutdown();
			}
        }
        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<String, Void, Bitmap> {
        private String url;
        private final WeakReference<ImageView> imageViewReference;

        public BitmapDownloaderTask(ImageView imageView) {
            imageViewReference = new WeakReference<ImageView>(imageView);
        }

        /**
         * Actual download method.
         */
        @Override
        protected Bitmap doInBackground(String... params) {
            url = params[0];
            return downloadBitmap(url);
        }

        /**
         * Once the image is downloaded, associates it to the imageView
         */
        @Override
        protected void onPostExecute(Bitmap bitmap) {
        	
        	
            if (isCancelled()) {
                bitmap = null;
            }
            
            addBitmapToCache(url, bitmap);

            if (imageViewReference != null) {
                ImageView imageView = imageViewReference.get();
                BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
                // Change bitmap only if this process is still associated with it
                // Or if we don't use any bitmap to task association (NO_DOWNLOADED_DRAWABLE mode)
                if (this == bitmapDownloaderTask) {
                	
                	if (bitmap != null) {
                		imageView.setImageBitmap(bitmap);
        			}else {
						imageView.setImageDrawable(mDefaultDrawable);//设置默认的图标
					}
                }                
            }
        }
    }


    /**
     * A fake Drawable that will be attached to the imageView while the download is in progress.
     *
     * <p>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.</p>
     */
    static class DownloadedDrawable extends ColorDrawable {
        private final WeakReference<BitmapDownloaderTask> bitmapDownloaderTaskReference;

        public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) {
            super(Color.TRANSPARENT);
            bitmapDownloaderTaskReference = new WeakReference<BitmapDownloaderTask>(bitmapDownloaderTask);
        }

        public BitmapDownloaderTask getBitmapDownloaderTask() {
            return bitmapDownloaderTaskReference.get();
        }
    }

    
    /*
     * Cache-related fields and methods.
     * 
     * We use a hard and a soft cache. A soft reference cache is too aggressively cleared by the
     * Garbage Collector.
     */
    
    private static final int HARD_CACHE_CAPACITY = 10;
    private static final int DELAY_BEFORE_PURGE = 10 * 1000; // in milliseconds

    // Hard cache, with a fixed maximum capacity and a life duration
    private final HashMap<String, Bitmap> sHardBitmapCache = new LinkedHashMap<String, Bitmap>(HARD_CACHE_CAPACITY / 2, 0.75f, true) {
	private static final long serialVersionUID = 1L;

		@Override
        protected boolean removeEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) {
            if (size() > HARD_CACHE_CAPACITY) {
                // Entries push-out of hard reference cache are transferred to soft reference cache
                sSoftBitmapCache.put(eldest.getKey(), new SoftReference<Bitmap>(eldest.getValue()));
                return true;
            } else
                return false;
        }
    };

    // Soft cache for bitmaps kicked out of hard cache
    private final static ConcurrentHashMap<String, SoftReference<Bitmap>> sSoftBitmapCache =
        new ConcurrentHashMap<String, SoftReference<Bitmap>>(HARD_CACHE_CAPACITY / 2);

    private final Handler purgeHandler = new Handler();

    private final Runnable purger = new Runnable() {
        public void run() {
            clearCache();
        }
    };

    /**
     * Adds this bitmap to the cache.
     * @param bitmap The newly downloaded bitmap.
     */
    private void addBitmapToCache(String url, Bitmap bitmap) {
        if (bitmap != null) {
            synchronized (sHardBitmapCache) {
                sHardBitmapCache.put(url, bitmap);
            }
        }
    }

    /**
     * @param url The URL of the image that will be retrieved from the cache.
     * @return The cached bitmap or null if it was not found.
     */
    private Bitmap getBitmapFromCache(String url) {
        // First try the hard reference cache
        synchronized (sHardBitmapCache) {
            final Bitmap bitmap = sHardBitmapCache.get(url);
            if (bitmap != null) {
                // Bitmap found in hard cache
                // Move element to first position, so that it is removed last
                sHardBitmapCache.remove(url);
                sHardBitmapCache.put(url, bitmap);
                return bitmap;
            }
        }

        // Then try the soft reference cache
        SoftReference<Bitmap> bitmapReference = sSoftBitmapCache.get(url);
        if (bitmapReference != null) {
            final Bitmap bitmap = bitmapReference.get();
            if (bitmap != null) {
                // Bitmap found in soft cache
                return bitmap;
            } else {
                // Soft reference has been Garbage Collected
                sSoftBitmapCache.remove(url);
            }
        }

        return null;
    }
 
    /**
     * Clears the image cache used internally to improve performance. Note that for memory
     * efficiency reasons, the cache will automatically be cleared after a certain inactivity delay.
     */
    private void clearCache() {
        sHardBitmapCache.clear();
        sSoftBitmapCache.clear();
    }

    /**
     * Allow a new delay before the automatic cache clear is done.
     */
    private void resetPurgeTimer() {
        purgeHandler.removeCallbacks(purger);
        purgeHandler.postDelayed(purger, DELAY_BEFORE_PURGE);
    }
    
    /**
     * Description: 设置默认图标
    * @param imageView
    * @param drawable 如果为null, 那么当图标下载失败的时候,显示的图标则为空白, 否则显示设置的图标。
     */
    private void setImageDefault(ImageView imageView ,Drawable drawable) {
    	this.mDefaultDrawable = drawable;
		if (imageView != null) {
			imageView.setImageDrawable(drawable);
		}
	}
    
}

在Adapter中进行调用ImageDownloader.getInstance().download( url ,holder.imageView,getContext().getResources().getDrawable(R.drawable.default_icon));


原文出处 : http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html


浏览并下载网页上的图片。 Image Downloader不出售,并且将始终是免费,开源的,并且没有广告或任何形式的跟踪算法! 您可以在此处找到源代码:https://github.com/vdsabev/image-downloader Image Downloader =================如果您需要从网页批量下载图像,使用此扩展程序,您可以:-查看页面包含的图像以及链接到的图像-按宽度,高度和URL进行过滤; 支持通配符和正则表达式-(可选)仅显示链接中的图像-通过单击图像选择要下载的图像-使用专用按钮下载或在新标签页中打开单个图像-自定义图像的显示宽度,列,边框大小和颜色-隐藏过滤器,不需要的按钮和通知按下“下载”按钮时,所有选定的图像都将保存到Chrome的默认下载目录,或者如果指定子文件夹名称,则保存到其中的目录。 警告:如果尚未设置默认的下载目录,则必须手动选择每个图像的保存位置,这可能会打开许多​​弹出窗口。 不建议您尝试一次在没有默认下载目录的情况下一次下载太多图像。 已知问题===============此扩展程序无法始终提取单击照片时打开的全分辨率图像(例如,在Facebook相册中)。 那是因为页面没有直接链接到图像,而是使用了脚本。 如果您需要那种功能,那么即使您无法大量下载图像,也可以使用诸如Hover Zoom的其他扩展。 更改日志=============== 2.4.2:-Chrome不允许访问跨域CSS规则的解决方法2.4.1:-修复了无效URL会破坏扩展名的问题- https://github.com/vdsabev/image-downloader/issues/23-将Zepto.js更新为1.2.0 2.4:-添加了在下载2.3前重命名文件的选项:-添加了对BMP,SVG和WebP图像的支持-增加了对相对URL的支持-通过搜索更少的元素提高了弹出窗口的加载速度-用chrome.runtime 2.2代替了不推荐使用的chrome.extension调用:-删除了访问标签的不必要权限-删除了由于提示而导致的捐赠提示一些用户认为它在第一次出现后并没有消失; 现在,将在首次安装时打开选项页-保存URL过滤器的值-修复某些尺寸调整问题的另一种尝试2.1:-添加了图像宽度/高度过滤器-由于某些原因,一次性重置了所有设置遇到尺寸问题的人-删除了按URL排序选项2.0:-添加了将文件保存到子文件夹的功能-利用Google Chrome下载API-实施了基于网格的更简洁设计-单击图像URL文本框现在将自动选择文本以便用户可以复制文本-修复了一些小的显示问题-添加了列数设置,删除了边框样式设置-选项页1.3中添加了捐赠按钮:-现在,样式标签中使用的图像也将包含在列表的末尾。 仅包含来自元素的内联样式属性的图像。 -新增了对数据URI的支持-若干错误修复和优化1.2:-更改了要显示在只读文本框中的图像上方的URL-将图像复选框移至顶部,并在每个图像复选框下方添加了打开和下载按钮-最初禁用了“下载”按钮和“所有”复选框-引入了一些新选项来隐藏过滤器,按钮和通知-删除了正文宽度选项; 弹出窗口的宽度现在相对于最大图像宽度选项重新调整大小-简化了设计1.1:-修复了最小和最大图像宽度的保存-在图像本身上方添加了URL以及用于切换的选项-添加了通配符过滤器模式(沿正常和正则表达式)-现在将保存所选过滤器的状态-将“按URL排序”选项移回过滤器-在选项页面中添加了“清除数据”按钮。 尽管该扩展程序尚未使用大量本地存储,但有人可能会喜欢此选项。 -重构了大量代码,尤其是本地存储1.0.13的使用:-添加了一条通知,使用户知道下载已开始-添加了一些动画并进一步完善了选项通知-修复了一些正在处理的事件处理程序多次附加1.0.12:-迁移到jQuery-为“所有”复选框实现了不确定的状态-如果未选中任何图像,则将禁用“下载”按钮-修复了带有重置选项的错误-现在用户可以选择保存重置值或只是通过重新加载页面来取消重置-就像通知1.0.11中所述:-更改了下载机制以支持Chrome v21 +-添加了“仅显示链接的图像”过滤器选项,当您只想下载页面上URL中的图像。 1.0.10:-添加了下载确认1.0.9:-图片数量现在将显示在“所有”复选框1.0.8旁:-添加了对锚定标记中的图片URL的检测; 请注意,此功能将不会检测不具有.jpg,.jpeg,.gif或.png文件扩展名的URL-它依赖于正则表达式,以避免可能向外部服务器发送1.0.7的数百个请求:-已删除当您按下“下载”时弹出的桌面通知系统,显示的文字描述应该易于控制(通过“选项”)并且不易受到干扰; 这也需要较少的扩展权限-添加了隐藏下载通知的选项; 大
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值