建立一個方法類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;
}
}