懒加载ImageLoader的应用

来源:互联网 发布:曲线图制作软件 编辑:程序博客网 时间:2024/05/16 05:36

            创建一个方法类ImageLoader,构造函数含有三个参数:图片地址 Url、图片对象 ImageVIew、是否只从缓存中获取 fromCache;

           private ImageLoader mImageLoader;

       mImageLoader.DisplayImage(url, viewHolder.comment_item_img, false);

       

     public class ImageLoader {

     private MemoryCache memoryCache = new MemoryCache();
private AbstractFileCache fileCache;
private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
// 线程池
private ExecutorService executorService;


public ImageLoader(Context context) {
fileCache = new FileCache(context);
//建立一个固定的线程池的大小
executorService = Executors.newFixedThreadPool(5);
}


    // 最主要的方法
public void DisplayImage(String url, ImageView imageView, boolean isLoadOnlyFromCache) {
imageViews.put(imageView, url);
// 先从内存缓存中查找


Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else if (!isLoadOnlyFromCache) {
// 若没有的话则开启新线程加载图片
queuePhoto(url, imageView);
}
}

    

    

      private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}


private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// 先从文件缓存中查找是否有
Bitmap b = null;
if (f != null && f.exists()) {
b = decodeFile(f);
}
if (b != null) {
return b;
}
// 最后从指定的url中下载图片
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);


conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
Log.e("", "getBitmap catch Exception...\nmessage = " + ex.getMessage());
return null;
}
}

    

原创粉丝点击