Android之ListView异步加载网络图片(优化缓存机制)

网上关于这个方面的文章也很多,基本的思路是线程+缓存来解决。下面提出一些优化:java

一、采用线程池android

二、内存缓存+文件缓存缓存

三、内存缓存中网上不少是采用SoftReference来防止堆溢出,这儿严格限制只能使用最大JVM内存的1/4ide

四、对下载的图片进行按比例缩放,以减小内存的消耗优化

具体的代码里面说明。先放上内存缓存类的代码MemoryCache.Javathis

 

[java] view plain copy print?url

  1. public class MemoryCache { 
  2.  
  3.     private static final String TAG = "MemoryCache"; 
  4.     // 放入缓存时是个同步操做 
  5.     // LinkedHashMap构造方法的最后一个参数true表明这个map里的元素将按照最近使用次数由少到多排列,即LRU 
  6.     // 这样的好处是若是要将缓存中的元素替换,则先遍历出最近最少使用的元素来替换以提升效率 
  7.     private Map<String, Bitmap> cache = Collections 
  8.             .synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true)); 
  9.     // 缓存中图片所占用的字节,初始0,将经过此变量严格控制缓存所占用的堆内存 
  10.     private long size = 0;// current allocated size 
  11.     // 缓存只能占用的最大堆内存 
  12.     private long limit = 1000000;// max memory in bytes 
  13.  
  14.     public MemoryCache() { 
  15.         // use 25% of available heap size 
  16.         setLimit(Runtime.getRuntime().maxMemory() / 4); 
  17.     } 
  18.  
  19.     public void setLimit(long new_limit) {  
  20.         limit = new_limit; 
  21.         Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB"); 
  22.     } 
  23.  
  24.     public Bitmap get(String id) { 
  25.         try { 
  26.             if (!cache.containsKey(id)) 
  27.                 return null; 
  28.             return cache.get(id); 
  29.         } catch (NullPointerException ex) { 
  30.             return null; 
  31.         } 
  32.     } 
  33.  
  34.     public void put(String id, Bitmap bitmap) { 
  35.         try { 
  36.             if (cache.containsKey(id)) 
  37.                 size -= getSizeInBytes(cache.get(id)); 
  38.             cache.put(id, bitmap); 
  39.             size += getSizeInBytes(bitmap); 
  40.             checkSize(); 
  41.         } catch (Throwable th) { 
  42.             th.printStackTrace(); 
  43.         } 
  44.     } 
  45.  
  46.     /**
  47.      * 严格控制堆内存,若是超过将首先替换最近最少使用的那个图片缓存
  48.      * 
  49.      */ 
  50.     private void checkSize() { 
  51.         Log.i(TAG, "cache size=" + size + " length=" + cache.size()); 
  52.         if (size > limit) { 
  53.             // 先遍历最近最少使用的元素 
  54.             Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator(); 
  55.             while (iter.hasNext()) { 
  56.                 Entry<String, Bitmap> entry = iter.next(); 
  57.                 size -= getSizeInBytes(entry.getValue()); 
  58.                 iter.remove(); 
  59.                 if (size <= limit) 
  60.                     break; 
  61.             } 
  62.             Log.i(TAG, "Clean cache. New size " + cache.size()); 
  63.         } 
  64.     } 
  65.  
  66.     public void clear() { 
  67.         cache.clear(); 
  68.     } 
  69.  
  70.     /**
  71.      * 图片占用的内存
  72.      * 
  73.      * @param bitmap
  74.      * @return
  75.      */ 
  76.     long getSizeInBytes(Bitmap bitmap) { 
  77.         if (bitmap == null) 
  78.             return 0; 
  79.         return bitmap.getRowBytes() * bitmap.getHeight(); 
  80.     } 
public class MemoryCache {

	private static final String TAG = "MemoryCache";
	// 放入缓存时是个同步操做
	// LinkedHashMap构造方法的最后一个参数true表明这个map里的元素将按照最近使用次数由少到多排列,即LRU
	// 这样的好处是若是要将缓存中的元素替换,则先遍历出最近最少使用的元素来替换以提升效率
	private Map<String, Bitmap> cache = Collections
			.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
	// 缓存中图片所占用的字节,初始0,将经过此变量严格控制缓存所占用的堆内存
	private long size = 0;// current allocated size
	// 缓存只能占用的最大堆内存
	private long limit = 1000000;// max memory in bytes

	public MemoryCache() {
		// use 25% of available heap size
		setLimit(Runtime.getRuntime().maxMemory() / 4);
	}

	public void setLimit(long new_limit) { 
		limit = new_limit;
		Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
	}

	public Bitmap get(String id) {
		try {
			if (!cache.containsKey(id))
				return null;
			return cache.get(id);
		} catch (NullPointerException ex) {
			return null;
		}
	}

	public void put(String id, Bitmap bitmap) {
		try {
			if (cache.containsKey(id))
				size -= getSizeInBytes(cache.get(id));
			cache.put(id, bitmap);
			size += getSizeInBytes(bitmap);
			checkSize();
		} catch (Throwable th) {
			th.printStackTrace();
		}
	}

	/**
	 * 严格控制堆内存,若是超过将首先替换最近最少使用的那个图片缓存
	 * 
	 */
	private void checkSize() {
		Log.i(TAG, "cache size=" + size + " length=" + cache.size());
		if (size > limit) {
			// 先遍历最近最少使用的元素
			Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
			while (iter.hasNext()) {
				Entry<String, Bitmap> entry = iter.next();
				size -= getSizeInBytes(entry.getValue());
				iter.remove();
				if (size <= limit)
					break;
			}
			Log.i(TAG, "Clean cache. New size " + cache.size());
		}
	}

	public void clear() {
		cache.clear();
	}

	/**
	 * 图片占用的内存
	 * 
	 * @param bitmap
	 * @return
	 */
	long getSizeInBytes(Bitmap bitmap) {
		if (bitmap == null)
			return 0;
		return bitmap.getRowBytes() * bitmap.getHeight();
	}
}

也可使用SoftReference,代码会简单不少,可是我推荐上面的方法。.net

 

[java] view plain copy print?线程

  1. public class MemoryCache { 
  2.      
  3.     private Map<String, SoftReference<Bitmap>> cache = Collections 
  4.             .synchronizedMap(new HashMap<String, SoftReference<Bitmap>>()); 
  5.  
  6.     public Bitmap get(String id) { 
  7.         if (!cache.containsKey(id)) 
  8.             return null; 
  9.         SoftReference<Bitmap> ref = cache.get(id); 
  10.         return ref.get(); 
  11.     } 
  12.  
  13.     public void put(String id, Bitmap bitmap) { 
  14.         cache.put(id, new SoftReference<Bitmap>(bitmap)); 
  15.     } 
  16.  
  17.     public void clear() { 
  18.         cache.clear(); 
  19.     } 
  20.  
public class MemoryCache {
	
	private Map<String, SoftReference<Bitmap>> cache = Collections
			.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());

	public Bitmap get(String id) {
		if (!cache.containsKey(id))
			return null;
		SoftReference<Bitmap> ref = cache.get(id);
		return ref.get();
	}

	public void put(String id, Bitmap bitmap) {
		cache.put(id, new SoftReference<Bitmap>(bitmap));
	}

	public void clear() {
		cache.clear();
	}

}

下面是文件缓存类的代码FileCache.java:code

 

 

[java] view plain copy print?

  1. public class FileCache { 
  2.  
  3.     private File cacheDir; 
  4.  
  5.     public FileCache(Context context) { 
  6.         // 若是有SD卡则在SD卡中建一个LazyList的目录存放缓存的图片 
  7.         // 没有SD卡就放在系统的缓存目录中 
  8.         if (android.os.Environment.getExternalStorageState().equals( 
  9.                 android.os.Environment.MEDIA_MOUNTED)) 
  10.             cacheDir = new File( 
  11.                     android.os.Environment.getExternalStorageDirectory(), 
  12.                     "LazyList"); 
  13.         else 
  14.             cacheDir = context.getCacheDir(); 
  15.         if (!cacheDir.exists()) 
  16.             cacheDir.mkdirs(); 
  17.     } 
  18.  
  19.     public File getFile(String url) { 
  20.         // 将url的hashCode做为缓存的文件名 
  21.         String filename = String.valueOf(url.hashCode()); 
  22.         // Another possible solution 
  23.         // String filename = URLEncoder.encode(url); 
  24.         File f = new File(cacheDir, filename); 
  25.         return f; 
  26.  
  27.     } 
  28.  
  29.     public void clear() { 
  30.         File[] files = cacheDir.listFiles(); 
  31.         if (files == null) 
  32.             return; 
  33.         for (File f : files) 
  34.             f.delete(); 
  35.     } 
  36.  
public class FileCache {

	private File cacheDir;

	public FileCache(Context context) {
		// 若是有SD卡则在SD卡中建一个LazyList的目录存放缓存的图片
		// 没有SD卡就放在系统的缓存目录中
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED))
			cacheDir = new File(
					android.os.Environment.getExternalStorageDirectory(),
					"LazyList");
		else
			cacheDir = context.getCacheDir();
		if (!cacheDir.exists())
			cacheDir.mkdirs();
	}

	public File getFile(String url) {
		// 将url的hashCode做为缓存的文件名
		String filename = String.valueOf(url.hashCode());
		// Another possible solution
		// String filename = URLEncoder.encode(url);
		File f = new File(cacheDir, filename);
		return f;

	}

	public void clear() {
		File[] files = cacheDir.listFiles();
		if (files == null)
			return;
		for (File f : files)
			f.delete();
	}

}

最后最重要的加载图片的类,ImageLoader.java:

 

 

[java] view plain copy print?

  1. public class ImageLoader { 
  2.  
  3.     MemoryCache memoryCache = new MemoryCache(); 
  4.     FileCache fileCache; 
  5.     private Map<ImageView, String> imageViews = Collections 
  6.             .synchronizedMap(new WeakHashMap<ImageView, String>()); 
  7.     // 线程池 
  8.     ExecutorService executorService; 
  9.  
  10.     public ImageLoader(Context context) { 
  11.         fileCache = new FileCache(context); 
  12.         executorService = Executors.newFixedThreadPool(5); 
  13.     } 
  14.  
  15.     // 当进入listview时默认的图片,可换成你本身的默认图片 
  16.     final int stub_id = R.drawable.stub; 
  17.  
  18.     // 最主要的方法 
  19.     public void DisplayImage(String url, ImageView imageView) { 
  20.         imageViews.put(imageView, url); 
  21.         // 先从内存缓存中查找 
  22.  
  23.         Bitmap bitmap = memoryCache.get(url); 
  24.         if (bitmap != null) 
  25.             imageView.setImageBitmap(bitmap); 
  26.         else { 
  27.             // 若没有的话则开启新线程加载图片 
  28.             queuePhoto(url, imageView); 
  29.             imageView.setImageResource(stub_id); 
  30.         } 
  31.     } 
  32.  
  33.     private void queuePhoto(String url, ImageView imageView) { 
  34.         PhotoToLoad p = new PhotoToLoad(url, imageView); 
  35.         executorService.submit(new PhotosLoader(p)); 
  36.     } 
  37.  
  38.     private Bitmap getBitmap(String url) { 
  39.         File f = fileCache.getFile(url); 
  40.  
  41.         // 先从文件缓存中查找是否有 
  42.         Bitmap b = decodeFile(f); 
  43.         if (b != null) 
  44.             return b; 
  45.  
  46.         // 最后从指定的url中下载图片 
  47.         try { 
  48.             Bitmap bitmap = null; 
  49.             URL imageUrl = new URL(url); 
  50.             HttpURLConnection conn = (HttpURLConnection) imageUrl 
  51.                     .openConnection(); 
  52.             conn.setConnectTimeout(30000); 
  53.             conn.setReadTimeout(30000); 
  54.             conn.setInstanceFollowRedirects(true); 
  55.             InputStream is = conn.getInputStream(); 
  56.             OutputStream os = new FileOutputStream(f); 
  57.             CopyStream(is, os); 
  58.             os.close(); 
  59.             bitmap = decodeFile(f); 
  60.             return bitmap; 
  61.         } catch (Exception ex) { 
  62.             ex.printStackTrace(); 
  63.             return null; 
  64.         } 
  65.     } 
  66.  
  67.     // decode这个图片而且按比例缩放以减小内存消耗,虚拟机对每张图片的缓存大小也是有限制的 
  68.     private Bitmap decodeFile(File f) { 
  69.         try { 
  70.             // decode image size 
  71.             BitmapFactory.Options o = new BitmapFactory.Options(); 
  72.             o.inJustDecodeBounds = true; 
  73.             BitmapFactory.decodeStream(new FileInputStream(f), null, o); 
  74.  
  75.             // Find the correct scale value. It should be the power of 2. 
  76.             final int REQUIRED_SIZE = 70; 
  77.             int width_tmp = o.outWidth, height_tmp = o.outHeight; 
  78.             int scale = 1; 
  79.             while (true) { 
  80.                 if (width_tmp / 2 < REQUIRED_SIZE 
  81.                         || height_tmp / 2 < REQUIRED_SIZE) 
  82.                     break; 
  83.                 width_tmp /= 2; 
  84.                 height_tmp /= 2; 
  85.                 scale *= 2; 
  86.             } 
  87.  
  88.             // decode with inSampleSize 
  89.             BitmapFactory.Options o2 = new BitmapFactory.Options(); 
  90.             o2.inSampleSize = scale; 
  91.             return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); 
  92.         } catch (FileNotFoundException e) { 
  93.         } 
  94.         return null; 
  95.     } 
  96.  
  97.     // Task for the queue 
  98.     private class PhotoToLoad { 
  99.         public String url; 
  100.         public ImageView imageView; 
  101.  
  102.         public PhotoToLoad(String u, ImageView i) { 
  103.             url = u; 
  104.             imageView = i; 
  105.         } 
  106.     } 
  107.  
  108.     class PhotosLoader implements Runnable { 
  109.         PhotoToLoad photoToLoad; 
  110.  
  111.         PhotosLoader(PhotoToLoad photoToLoad) { 
  112.             this.photoToLoad = photoToLoad; 
  113.         } 
  114.  
  115.         @Override 
  116.         public void run() { 
  117.             if (imageViewReused(photoToLoad)) 
  118.                 return; 
  119.             Bitmap bmp = getBitmap(photoToLoad.url); 
  120.             memoryCache.put(photoToLoad.url, bmp); 
  121.             if (imageViewReused(photoToLoad)) 
  122.                 return; 
  123.             BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad); 
  124.             // 更新的操做放在UI线程中 
  125.             Activity a = (Activity) photoToLoad.imageView.getContext(); 
  126.             a.runOnUiThread(bd); 
  127.         } 
  128.     } 
  129.  
  130.     /**
  131.      * 防止图片错位
  132.      * 
  133.      * @param photoToLoad
  134.      * @return
  135.      */ 
  136.     boolean imageViewReused(PhotoToLoad photoToLoad) { 
  137.         String tag = imageViews.get(photoToLoad.imageView); 
  138.         if (tag == null || !tag.equals(photoToLoad.url)) 
  139.             return true; 
  140.         return false; 
  141.     } 
  142.  
  143.     // 用于在UI线程中更新界面 
  144.     class BitmapDisplayer implements Runnable { 
  145.         Bitmap bitmap; 
  146.         PhotoToLoad photoToLoad; 
  147.  
  148.         public BitmapDisplayer(Bitmap b, PhotoToLoad p) { 
  149.             bitmap = b; 
  150.             photoToLoad = p; 
  151.         } 
  152.  
  153.         public void run() { 
  154.             if (imageViewReused(photoToLoad)) 
  155.                 return; 
  156.             if (bitmap != null) 
  157.                 photoToLoad.imageView.setImageBitmap(bitmap); 
  158.             else 
  159.                 photoToLoad.imageView.setImageResource(stub_id); 
  160.         } 
  161.     } 
  162.  
  163.     public void clearCache() { 
  164.         memoryCache.clear(); 
  165.         fileCache.clear(); 
  166.     } 
  167.  
  168.     public static void CopyStream(InputStream is, OutputStream os) { 
  169.         final int buffer_size = 1024; 
  170.         try { 
  171.             byte[] bytes = new byte[buffer_size]; 
  172.             for (;;) { 
  173.                 int count = is.read(bytes, 0, buffer_size); 
  174.                 if (count == -1) 
  175.                     break; 
  176.                 os.write(bytes, 0, count); 
  177.             } 
  178.         } catch (Exception ex) { 
  179.         } 
  180.     } 
public class ImageLoader {

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

	public ImageLoader(Context context) {
		fileCache = new FileCache(context);
		executorService = Executors.newFixedThreadPool(5);
	}

	// 当进入listview时默认的图片,可换成你本身的默认图片
	final int stub_id = R.drawable.stub;

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

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

	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 = 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) {
			ex.printStackTrace();
			return null;
		}
	}

	// decode这个图片而且按比例缩放以减小内存消耗,虚拟机对每张图片的缓存大小也是有限制的
	private Bitmap decodeFile(File f) {
		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 70;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}

	// Task for the queue
	private class PhotoToLoad {
		public String url;
		public ImageView imageView;

		public PhotoToLoad(String u, ImageView i) {
			url = u;
			imageView = i;
		}
	}

	class PhotosLoader implements Runnable {
		PhotoToLoad photoToLoad;

		PhotosLoader(PhotoToLoad photoToLoad) {
			this.photoToLoad = photoToLoad;
		}

		@Override
		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			Bitmap bmp = getBitmap(photoToLoad.url);
			memoryCache.put(photoToLoad.url, bmp);
			if (imageViewReused(photoToLoad))
				return;
			BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
			// 更新的操做放在UI线程中
			Activity a = (Activity) photoToLoad.imageView.getContext();
			a.runOnUiThread(bd);
		}
	}

	/**
	 * 防止图片错位
	 * 
	 * @param photoToLoad
	 * @return
	 */
	boolean imageViewReused(PhotoToLoad photoToLoad) {
		String tag = imageViews.get(photoToLoad.imageView);
		if (tag == null || !tag.equals(photoToLoad.url))
			return true;
		return false;
	}

	// 用于在UI线程中更新界面
	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		PhotoToLoad photoToLoad;

		public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
			bitmap = b;
			photoToLoad = p;
		}

		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			if (bitmap != null)
				photoToLoad.imageView.setImageBitmap(bitmap);
			else
				photoToLoad.imageView.setImageResource(stub_id);
		}
	}

	public void clearCache() {
		memoryCache.clear();
		fileCache.clear();
	}

	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}
}

主要流程是先从内存缓存中查找,若没有再开线程,从文件缓存中查找都没有则从指定的url中查找,并对bitmap进行处理,最后经过下面方法对UI进行更新操做。

[java] view plain copy print?

  1. a.runOnUiThread(...); 
a.runOnUiThread(...);

 

在你的程序中的基本用法:

 

[java] view plain copy print?

  1. ImageLoader imageLoader=new ImageLoader(context); 
  2. ... 
  3. imageLoader.DisplayImage(url, imageView); 
ImageLoader imageLoader=new ImageLoader(context);
...
imageLoader.DisplayImage(url, imageView);

好比你的放在你的ListView的adapter的getView()方法中,固然也适用于GridView。

 

OK,先到这。

相关文章
相关标签/搜索