`
jishublog
  • 浏览: 870024 次
文章分类
社区版块
存档分类
最新评论

Android 中加载网络资源时的优化 缓存和异步机制

 
阅读更多

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

1、采用线程池

2、内存缓存+文件缓存

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

4、对下载的图片进行按比例缩放,以减少内存的消耗

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

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,代码会简单很多,但是我推荐上面的方法。

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:

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:

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进行更新操作。

a.runOnUiThread(...);

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

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

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

分享到:
评论

相关推荐

    android异步加载网络图片,双缓存内存加sd卡缓存 绝对不会出现内存溢出oom

    很久没上传资源了,今天特意把自己收集的,自己用过的资源上传。Android 异步加载网络的图片,开始的时候显示默认的,当加载完成图片后替换掉原来的默认图片,绝对不会发生内存溢出的问题。

    Android 官方异步加载网络图片 写缓存

    Android官方提供的异步加载网络图片,通过缓存的模式实现。 真实不习惯网上很多下载资源都是用jar包封装起来,根本就没有什么参考价值,再则自己写的也不稳定。现在把Android官方异步加载网络图片打包为一个工程放到...

    Android项目异步加载图像小结 (含线程池,缓存方法).rar

    本资源为一份关于Android项目中异步加载图像的详细文档,包含了线程池和缓存方法的应用。文档旨在帮助开发者解决在Android应用中高效加载大量图像的问题,提高应用的性能和用户体验。 主要内容包括: 1. 异步加载...

    安卓异步加载网络资源(多线程&AsynvTask)

    本项目是根据慕课网《android必学-异步加载》视频教学所开发的一套异步加载网络资源的小demo.其中分别用到了多线程、AsyncTask实现异步加载的功能。 里面还包括了: json解析、网络请求、LruCache缓存、滚动优化等...

    Android网络图片异步加载实例

    开发Android程序,一般情况下都会有两个操作,图片的异步加载与缓存,而图片的异步加载大都是从网络读取图片(还有生成本地图片缩略图等操作),为了减少网络操作,加快图片加载速度就需要对图片进行缓存,所以网上...

    Android项目 Gallery实现异步加载网络图片 并只加载当前停止页面图.rar

    本项目为一款基于Android的Gallery应用,实现了异步加载网络图片的功能,同时具备仅加载当前停止页面图片的特性,有效节省用户流量和提高应用性能。 **功能特点**: 1. **异步加载**:利用Android的AsyncTask或...

    Android项目模仿易网新闻页面源码(异步加载).rar

    Android项目模仿易网新闻页面源码(异步加载) 本资源提供了一个高质量的Android项目源码,旨在帮助您轻松实现类似于易网的新闻页面效果。该项目采用异步加载技术,有效提高了页面加载速度和用户体验。同时,该项目...

    Android ThinkAndroid开发框架.zip

    具有快速构建文件缓存功能,无需考虑缓存文件的格式,都可以非常轻松的实现缓存,它还基于文件缓存模块实现了图片缓存功能, 在android中加载的图片的时候,对oom的问题,和对加载图片错位的问题都轻易解决。...

    Android 常用六大框架

    支持加载网络图片和本地图片; 内存管理使用lru算法,更好的管理bitmap内存; 可配置线程加载线程数量,缓存大小,缓存路径,加载显示动画等... 5、ThinkAndroid 项目地址:...

    Android项目源码ThinkAndroid开发框架.zip

    具有快速构建文件缓存功能,无需考虑缓存文件的格式,都可以非常轻松的实现缓存,它还基于文件缓存模块实现了图片缓存功能, 在android中加载的图片的时候,对oom的问题,和对加载图片错位的问题都轻易解决。...

    很牛逼的android开发包

    支持加载网络图片和本地图片; 内存管理使用lru算法,更好的管理bitmap内存; 可配置线程加载线程数量,缓存大小,缓存路径,加载显示动画等... 使用xUtils快速开发框架需要有以下权限: &lt;uses-permission android:...

    xUtils android开发框架

    ## 目前xUtils主要有四大模块: ... &gt; * 支持加载网络图片和本地图片; &gt; * 内存管理使用lru算法,更好的管理bitmap内存; &gt; * 可配置线程加载线程数量,缓存大小,缓存路径,加载显示动画等...

    Android-GridView-PhotoGallery:在内存和 SD 卡中保存图像的图像缓存扩展

    一个GridView照片列表的案例,异步加载网络图片的同时,使用LRU的缓存策略,通过内存与磁盘的二级缓存,实现GridView在滑动与加载图片时给予良好的用户体验. #Features 通过AsyncTask加载网络图片 Lru的缓存算法将...

    Android项目源码腾飞校园新闻客户端.zip

    怎样进行网络内容的异步加载以及数据缓存 怎样使用 Gradle 轻松完成项目的构建 怎样使用 PreferenceFragment 方便地完成设置界面 怎样使用 属性动画 项目中用到的开源库 Ultra Pull To Refresh 下拉刷新组件 ...

    xUtils 安卓类库框架开源

    支持加载网络图片和本地图片; 内存管理使用lru算法 更好的管理bitmap内存; 可配置线程加载线程数量 缓存大小 缓存路径 加载显示动画等 "&gt;xUtils简介 xUtils 包含了很多实用的android工具 xUtils 最初源于Afinal...

    安卓xUtils3最新demo例子

    android xutils 3.0 使用超详demo xUtils3-master.zipxUtils 一个 Android 公共库框架,主要包括四个部分:View,Db...而且支持图片的内存和本地缓存。 基于gradle3.3编译通过。使用命令gradle assembleDebug命令即可。

    Android项目源码24小时今日资讯新闻客户端

    Android项目源码24小时今日资讯新闻客户端 最新鲜的时事新闻,最时尚的手机科技,最好玩的热门游戏,还有各式各样的微博热点。 第一时间听到今日的最新资讯...[注意:本资源来自网络,如有侵权,请联系我删除,谢谢。]

    Android知识点及重要代码合集 word文档

    7.8 掌握AsyncTask异步任务下载网络资源 70 7.9 DatePickerDialog、TimePickerDialog的使用 76 8.1 ListView、SimpleAdapter和ArrayAdapter的使用 78 8.2 自定义适配器及BaseAdapter 83 8.3 ListView的缓存原理 85 ...

    xUtils jar包3个版本

    支持加载网络图片和本地图片; 内存管理使用lru算法,更好的管理bitmap内存; 可配置线程加载线程数量,缓存大小,缓存路径,加载显示动画等... 使用xUtils快速开发框架需要有以下权限: &lt;uses-permission android:...

    黑马程序员 安卓学院 万元哥项目经理 分享220个代码实例

    |--缓存优化之本地缓存优化(超过规定值或SD卡容量不够时) |--网络post提交查询请求 |--网络之HttpClient的get和post用法 |--网络之判断网络状态是否可用 |--网络之设置apn |--网络图片查看器 |--网络图片的下载与...

Global site tag (gtag.js) - Google Analytics