Android批量图片加载经典系列——采用二级缓存、异步加载网络图片
一、问题描述 |
Android应用中经常涉及从网络中加载大量图片,为提升加载速度和效率,减少网络流量都会采用二级缓存和异步加载机制,所谓二级缓存就是通过先从内存中获取、再从文件中获取,最后才会访问网络。内存缓存(一级)本质上是Map集合以key-value对的方式存储图片的url和Bitmap信息,由于内存缓存会造成堆内存泄露, 管理相对复杂一些,可采用第三方组件,对于有经验的可自己编写组件,而文件缓存比较简单通常自己封装一下即可。下面就通过案例看如何实现网络图片加载的优化。
二、案例介绍 |
案例新闻的列表图片
三、主要核心组件 |
下面先看看实现一级缓存(内存)、二级缓存(磁盘文件)所编写的组件
1、MemoryCache
在内存中存储图片(一级缓存), 采用了1个map来缓存图片代码如下:

- public class MemoryCache {
- // 最大的缓存数
- private static final int MAX_CACHE_CAPACITY = 30;
- //用Map软引用的Bitmap对象, 保证内存空间足够情况下不会被垃圾回收
- private HashMap<String, SoftReference<Bitmap>> mCacheMap =
- new LinkedHashMap<String, SoftReference<Bitmap>>() {
- private static final long serialVersionUID = 1L;
- //当缓存数量超过规定大小(返回true)会清除最早放入缓存的
- protected boolean removeEldestEntry(
- Map.Entry<String,SoftReference<Bitmap>> eldest){
- return size() > MAX_CACHE_CAPACITY;};
- };
- /**
- * 从缓存里取出图片
- * @param id
- * @return 如果缓存有,并且该图片没被释放,则返回该图片,否则返回null
- */
- public Bitmap get(String id){
- if(!mCacheMap.containsKey(id)) return null;
- SoftReference<Bitmap> ref = mCacheMap.get(id);
- return ref.get();
- }
- /**
- * 将图片加入缓存
- * @param id
- * @param bitmap
- */
- public void put(String id, Bitmap bitmap){
- mCacheMap.put(id, new SoftReference<Bitmap>(bitmap));
- }
- /**
- * 清除所有缓存
- */
- public void clear() {
- try {
- for(Map.Entry<String,SoftReference<Bitmap>>entry :mCacheMap.entrySet())
- { SoftReference<Bitmap> sr = entry.getValue();
- if(null != sr) {
- Bitmap bmp = sr.get();
- if(null != bmp) bmp.recycle();
- }
- }
- mCacheMap.clear();
- } catch (Exception e) {
- e.printStackTrace();}
- }
- }

2、FileCache
在磁盘中缓存图片(二级缓存),代码如下

- public class FileCache {
- //缓存文件目录
- private File mCacheDir;
- /**
- * 创建缓存文件目录,如果有SD卡,则使用SD,如果没有则使用系统自带缓存目录
- * @param context
- * @param cacheDir 图片缓存的一级目录
- */
- public FileCache(Context context, File cacheDir, String dir){
- if(android.os.Environment.getExternalStorageState().equals、(android.os.Environment.MEDIA_MOUNTED))
- mCacheDir = new File(cacheDir, dir);
- else
- mCacheDir = context.getCacheDir();// 如何获取系统内置的缓存存储路径
- if(!mCacheDir.exists()) mCacheDir.mkdirs();
- }
- public File getFile(String url){
- File f=null;
- try {
- //对url进行编辑,解决中文路径问题
- String filename = URLEncoder.encode(url,"utf-8");
- f = new File(mCacheDir, filename);
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return f;
- }
- public void clear(){//清除缓存文件
- File[] files = mCacheDir.listFiles();
- for(File f:files)f.delete();
- }
- }

3、编写异步加载组件AsyncImageLoader
android中采用单线程模型即应用运行在UI主线程中,且Android又是实时操作系统要求及时响应否则出现ANR错误,因此对于耗时操作要求不能阻塞UI主线程,需要开启一个线程处理(如本应用中的图片加载)并将线程放入队列中,当运行完成后再通知UI主线程进行更改,同时移除任务——这就是异步任务,在android中实现异步可通过本系列一中所用到的AsyncTask或者使用thread+handler机制,在这里是完全是通过代码编写实现的,这样我们可以更清晰的看到异步通信的实现的本质,代码如下

- public class AsyncImageLoader{
- private MemoryCache mMemoryCache;//内存缓存
- private FileCache mFileCache;//文件缓存
- private ExecutorService mExecutorService;//线程池
- //记录已经加载图片的ImageView
- private Map<ImageView, String> mImageViews = Collections
- .synchronizedMap(new WeakHashMap<ImageView, String>());
- //保存正在加载图片的url
- private List<LoadPhotoTask> mTaskQueue = new ArrayList<LoadPhotoTask>();
- /**
- * 默认采用一个大小为5的线程池
- * @param context
- * @param memoryCache 所采用的高速缓存
- * @param fileCache 所采用的文件缓存
- */
- public AsyncImageLoader(Context context, MemoryCache memoryCache, FileCache fileCache) {
- mMemoryCache = memoryCache;
- mFileCache = fileCache;
- mExecutorService = Executors.newFixedThreadPool(5);//建立一个容量为5的固定尺寸的线程池(最大正在运行的线程数量)
- }
- /**
- * 根据url加载相应的图片
- * @param url
- * @return 先从一级缓存中取图片有则直接返回,如果没有则异步从文件(二级缓存)中取,如果没有再从网络端获取
- */
- public Bitmap loadBitmap(ImageView imageView, String url) {
- //先将ImageView记录到Map中,表示该ui已经执行过图片加载了
- mImageViews.put(imageView, url);
- Bitmap bitmap = mMemoryCache.get(url);//先从一级缓存中获取图片
- if(bitmap == null) {
- enquequeLoadPhoto(url, imageView);//再从二级缓存和网络中获取
- }
- return bitmap;
- }
- /**
- * 加入图片下载队列
- * @param url
- */
- private void enquequeLoadPhoto(String url, ImageView imageView) {
- //如果任务已经存在,则不重新添加
- if(isTaskExisted(url))
- return;
- LoadPhotoTask task = new LoadPhotoTask(url, imageView);
- synchronized (mTaskQueue) {
- mTaskQueue.add(task);//将任务添加到队列中
- }
- mExecutorService.execute(task);//向线程池中提交任务,如果没有达到上限(5),则运行否则被阻塞
- }
- /**
- * 判断下载队列中是否已经存在该任务
- * @param url
- * @return
- */
- private boolean isTaskExisted(String url) {
- if(url == null)
- return false;
- synchronized (mTaskQueue) {
- int size = mTaskQueue.size();
- for(int i=0; i<size; i++) {
- LoadPhotoTask task = mTaskQueue.get(i);
- if(task != null && task.getUrl().equals(url))
- return true;
- }
- }
- return false;
- }
- /**
- * 从缓存文件或者网络端获取图片
- * @param url
- */
- private Bitmap getBitmapByUrl(String url) {
- File f = mFileCache.getFile(url);//获得缓存图片路径
- Bitmap b = ImageUtil.decodeFile(f);//获得文件的Bitmap信息
- if (b != null)//不为空表示获得了缓存的文件
- return b;
- return ImageUtil.loadBitmapFromWeb(url, f);//同网络获得图片
- }
- /**
- * 判断该ImageView是否已经加载过图片了(可用于判断是否需要进行加载图片)
- * @param imageView
- * @param url
- * @return
- */
- private boolean imageViewReused(ImageView imageView, String url) {
- String tag = mImageViews.get(imageView);
- if (tag == null || !tag.equals(url))
- return true;
- return false;
- }
- private void removeTask(LoadPhotoTask task) {
- synchronized (mTaskQueue) {
- mTaskQueue.remove(task);
- }
- }
- class LoadPhotoTask implements Runnable {
- private String url;
- private ImageView imageView;
- LoadPhotoTask(String url, ImageView imageView) {
- this.url = url;
- this.imageView = imageView;
- }
- @Override
- public void run() {
- if (imageViewReused(imageView, url)) {//判断ImageView是否已经被复用
- removeTask(this);//如果已经被复用则删除任务
- return;
- }
- Bitmap bmp = getBitmapByUrl(url);//从缓存文件或者网络端获取图片
- mMemoryCache.put(url, bmp);// 将图片放入到一级缓存中
- if (!imageViewReused(imageView, url)) {//若ImageView未加图片则在ui线程中显示图片
- BitmapDisplayer bd = new BitmapDisplayer(bmp, imageView, url); Activity a = (Activity) imageView.getContext();
- a.runOnUiThread(bd);//在UI线程调用bd组件的run方法,实现为ImageView控件加载图片
- }
- removeTask(this);//从队列中移除任务
- }
- public String getUrl() {
- return url;
- }
- }
- /**
- *
- *由UI线程中执行该组件的run方法
- */
- class BitmapDisplayer implements Runnable {
- private Bitmap bitmap;
- private ImageView imageView;
- private String url;
- public BitmapDisplayer(Bitmap b, ImageView imageView, String url) {
- bitmap = b;
- this.imageView = imageView;
- this.url = url;
- }
- public void run() {
- if (imageViewReused(imageView, url))
- return;
- if (bitmap != null)
- imageView.setImageBitmap(bitmap);
- }
- }
- /**
- * 释放资源
- */
- public void destroy() {
- mMemoryCache.clear();
- mMemoryCache = null;
- mImageViews.clear();
- mImageViews = null;
- mTaskQueue.clear();
- mTaskQueue = null;
- mExecutorService.shutdown();
- mExecutorService = null;
- }
- }

编写完成之后,对于异步任务的执行只需调用AsyncImageLoader中的loadBitmap()方法即可非常方便,对于AsyncImageLoader组件的代码最好结合注释好好理解一下,这样对于Android中线程之间的异步通信就会有深刻的认识。
4、工具类ImageUtil

- public class ImageUtil {
- /**
- * 从网络获取图片,并缓存在指定的文件中
- * @param url 图片url
- * @param file 缓存文件
- * @return
- */
- public static Bitmap loadBitmapFromWeb(String url, File file) {
- HttpURLConnection conn = null;
- InputStream is = null;
- OutputStream os = null;
- try {
- Bitmap bitmap = null;
- URL imageUrl = new URL(url);
- conn = (HttpURLConnection) imageUrl.openConnection();
- conn.setConnectTimeout(30000);
- conn.setReadTimeout(30000);
- conn.setInstanceFollowRedirects(true);
- is = conn.getInputStream();
- os = new FileOutputStream(file);
- copyStream(is, os);//将图片缓存到磁盘中
- bitmap = decodeFile(file);
- return bitmap;
- } catch (Exception ex) {
- ex.printStackTrace();
- return null;
- } finally {
- try {
- if(os != null) os.close();
- if(is != null) is.close();
- if(conn != null) conn.disconnect();
- } catch (IOException e) { }
- }
- }
- public static Bitmap decodeFile(File f) {
- try {
- return BitmapFactory.decodeStream(new FileInputStream(f), null, null);
- } catch (Exception e) { }
- return null;
- }
- private 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) {
- ex.printStackTrace();
- }
- }
- }

四、测试应用 |
组件之间的时序图:
1、编写MainActivity

- public class MainActivity extends Activity {
- ListView list;
- ListViewAdapter adapter;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- list=(ListView)findViewById(R.id.list);
- adapter=new ListViewAdapter(this, mStrings);
- list.setAdapter(adapter);
- }
- public void onDestroy(){
- list.setAdapter(null);
- super.onDestroy();
- adapter.destroy();
- }
- private String[] mStrings={
- "http://news.21-sun.com/UserFiles/x_Image/x_20150606083511_0.jpg",
- "http://news.21-sun.com/UserFiles/x_Image/x_20150606082847_0.jpg",
- …..};
- }

2、编写适配器

- public class ListViewAdapter extends BaseAdapter {
- private Activity mActivity;
- private String[] data;
- private static LayoutInflater inflater=null;
- private AsyncImageLoader imageLoader;//异步组件
- public ListViewAdapter(Activity mActivity, String[] d) {
- this.mActivity=mActivity;
- data=d;
- inflater = (LayoutInflater)mActivity.getSystemService(
- Context.LAYOUT_INFLATER_SERVICE);
- MemoryCache mcache=new MemoryCache();//内存缓存
- File sdCard = android.os.Environment.getExternalStorageDirectory();//获得SD卡
- File cacheDir = new File(sdCard, "jereh_cache" );//缓存根目录
- FileCache fcache=new FileCache(mActivity, cacheDir, "news_img");//文件缓存
- imageLoader = new AsyncImageLoader(mActivity, mcache,fcache);
- }
- public int getCount() {
- return data.length;
- }
- public Object getItem(int position) {
- return position;
- }
- public long getItemId(int position) {
- return position;
- }
- public View getView(int position, View convertView, ViewGroup parent) {
- ViewHolder vh=null;
- if(convertView==null){
- convertView = inflater.inflate(R.layout.item, null);
- vh=new ViewHolder();
- vh.tvTitle=(TextView)convertView.findViewById(R.id.text);
- vh.ivImg=(ImageView)convertView.findViewById(R.id.image);
- convertView.setTag(vh);
- }else{
- vh=(ViewHolder)convertView.getTag();
- }
- vh.tvTitle.setText("标题信息测试———— "+position);
- vh.ivImg.setTag(data[position]);
- //异步加载图片,先从一级缓存、再二级缓存、最后网络获取图片
- Bitmap bmp = imageLoader.loadBitmap(vh.ivImg, data[position]);
- if(bmp == null) {
- vh.ivImg.setImageResource(R.drawable.default_big);
- } else {
- vh.ivImg.setImageBitmap(bmp);
- }
- return convertView;
- }
- private class ViewHolder{
- TextView tvTitle;
- ImageView ivImg;
- }
- public void destroy() {
- imageLoader.destroy();
- }
- }

Android批量图片加载经典系列——采用二级缓存、异步加载网络图片的更多相关文章
- Android批量图片加载经典系列——使用二级缓存、异步网络负载形象
一.问题描写叙述 Android应用中常常涉及从网络中载入大量图片,为提升载入速度和效率,降低网络流量都会採用二级缓存和异步载入机制.所谓二级缓存就是通过先从内存中获取.再从文件里获取,最后才会訪问网 ...
- Android批量图片加载经典系列——使用LruCache、AsyncTask缓存并异步加载图片
一.问题描述 使用LruCache.AsyncTask实现批量图片的加载并达到下列技术要求 1.从缓存中读取图片,若不在缓存中,则开启异步线程(AsyncTask)加载图片,并放入缓存中 2.及时移除 ...
- Android批量图片加载经典系列——使用xutil框架缓存、异步加载网络图片
一.问题描述 为提高图片加载的效率,需要对图片的采用缓存和异步加载策略,编码相对比较复杂,实际上有一些优秀的框架提供了解决方案,比如近期在git上比较活跃的xutil框架 Xutil框架提供了四大模块 ...
- Android批量图片加载经典系列——afinal框架实现图片的异步缓存加载
一.问题描述 在之前的系列文章中,我们使用了Volley和Xutil框架实现图片的缓存加载(查看系列文章:http://www.cnblogs.com/jerehedu/p/4607599.html# ...
- Android批量图片加载经典系列——Volley框架实现多布局的新闻列表
一.问题描述 Volley是Google 2013年发布的实现Android平台上的网络通信库,主要提供网络通信和图片下载的解决方案,比如以前从网上下载图片的步骤可能是这样的流程: 在ListAdap ...
- Android批量图片载入经典系列——使用LruCache、AsyncTask缓存并异步载入图片
一.问题描写叙述 使用LruCache.AsyncTask实现批量图片的载入并达到下列技术要求 1.从缓存中读取图片,若不在缓存中,则开启异步线程(AsyncTask)载入图片,并放入缓存中 2.及时 ...
- Android图片管理组件(双缓存+异步加载)
转自:http://www.oschina.net/code/snippet_219356_18887?p=3#comments ImageManager2这个类具有异步从网络下载图片,从sd读取本地 ...
- Android批量图片载入经典系列——afinal框架实现图片的异步缓存载入
一.问题描写叙述 在之前的系列文章中,我们使用了Volley和Xutil框架实现图片的缓存载入,接下来我们再介绍一下afinal 框架的使用. Afinal 是一个android的http框架.sql ...
- Android批量图片载入经典系列——Volley框架实现多布局的新闻列表
一.问题描写叙述 Volley是Google 2013年公布的实现Android平台上的网络通信库,主要提供网络通信和图片下载的解决方式,比方曾经从网上下载图片的步骤可能是这种流程: 在ListAda ...
随机推荐
- python: hashlib 加密模块
加密模块hashlib import hashlib m=hashlib.md5() m.update(b'hello') print(m.hexdigest()) #十六进制加密 m.update( ...
- ThreadLocal的使用及介绍
ThreadLocal总结 1.ThreadLocal使用场合主要解决多线程中数据数据因并发产生不一致问题.ThreadLocal为每个线程的中并发访问的数据提供一个副本,通过访问副本来运行业务,这样 ...
- 20150608_Andriod 发布问题处理
参考地址: http://blog.csdn.net/cxc19890214/article/details/39120415 问题:当我们开发完成一个Android应用程序后,在发布该应用程序之前必 ...
- Python学习笔记-Day2-Python基础之列表操作
列表的常用操作包括但不限于以下操作: 列表的索引,切片,追加,删除,切片等 这里将对列表的内置操作方法进行总结归纳,重点是以示例的方式进行展示. 使用type获取创建对象的类 type(list) 使 ...
- ural 1110,快速幂
题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1110 题意: X^N % M = Y,X=[0,M-1];没有输出-1: #incl ...
- thinkphp nginx 配置
thinkphp convention配置:'URL_MODEL' => '2', //URL模式 nginx rewrite配置: if (!-e $request_filename) { r ...
- 【leetcode❤python】 19. Remove Nth Node From End of List
#-*- coding: UTF-8 -*-#双指针思想,两个指针相隔n-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针的后继就是要删除的节点# Definition for sin ...
- 【Unity3D游戏开发】性能优化之spine提高80~90%的效率 (三一)
Spine效率低 Unity项目加载spine动画,经常会出现卡顿的情况,如游戏中瞬间播放一个动画,打开一个带spine动画的界面.尤其是SkeletonRenderer.Awake时,会瞬间出现大量 ...
- Sql合并两个select查询
现有2个查询,需要将每个查询的结果合并起来(注意不是合并结果集,因此不能使用union),可以将每个查询的结果作为临时表,然后再从临时表中select所需的列,示例如下: SELECT get.d ...
- Printing Array elements with Comma delimiters
https://www.codewars.com/kata/printing-array-elements-with-comma-delimiters/train/csharp using Syste ...