Android图片加载:采用二级缓存、异步加载网络图片

移动开发 Android
Android应用中经常涉及从网络中加载大量图片,为提升加载速度和效率,减少网络流量都会采用二级缓存和异步加载机制,所谓二级缓存就是通过先从内存中获取、再从文件中获取,最后才会访问网络。

一、问题描述

Android应用中经常涉及从网络中加载大量图片,为提升加载速度和效率,减少网络流量都会采用二级缓存和异步加载机制,所谓二级缓存就是通过先从内存中获取、再从文件中获取,***才会访问网络。内存缓存(一级)本质上是Map集合以key-value对的方式存储图片的url和Bitmap信息,由于内存缓存会造成堆内存泄露, 管理相对复杂一些,可采用第三方组件,对于有经验的可自己编写组件,而文件缓存比较简单通常自己封装一下即可。下面就通过案例看如何实现网络图片加载的优化。

二、案例介绍

案例新闻的列表图片

三、主要核心组件

下面先看看实现一级缓存(内存)、二级缓存(磁盘文件)所编写的组件

1、MemoryCache

在内存中存储图片(一级缓存), 采用了1个map来缓存图片代码如下:

  1. public class MemoryCache { 
  2. // ***的缓存数 
  3. private static final int MAX_CACHE_CAPACITY = 30
  4. //用Map软引用的Bitmap对象, 保证内存空间足够情况下不会被垃圾回收 
  5. private HashMap<String, SoftReference<Bitmap>> mCacheMap = 
  6. new LinkedHashMap<String, SoftReference<Bitmap>>() { 
  7. private static final long serialVersionUID = 1L; 
  8. //当缓存数量超过规定大小(返回true)会清除最早放入缓存的 
  9. protected boolean removeEldestEntry( 
  10. Map.Entry<String,SoftReference<Bitmap>> eldest){ 
  11. return size() > MAX_CACHE_CAPACITY;}; 
  12. }; 
  13.  
  14. /** 
  15. * 从缓存里取出图片 
  16. * @param id 
  17. * @return 如果缓存有,并且该图片没被释放,则返回该图片,否则返回null 
  18. */ 
  19. public Bitmap get(String id){ 
  20. if(!mCacheMap.containsKey(id)) return null
  21. SoftReference<Bitmap> ref = mCacheMap.get(id); 
  22. return ref.get(); 
  23.  
  24. /** 
  25. * 将图片加入缓存 
  26. * @param id 
  27. * @param bitmap 
  28. */ 
  29. public void put(String id, Bitmap bitmap){ 
  30. mCacheMap.put(id, new SoftReference<Bitmap>(bitmap)); 
  31. /** 
  32. * 清除所有缓存 
  33. */ 
  34. public void clear() { 
  35. try { 
  36. for(Map.Entry<String,SoftReference<Bitmap>>entry :mCacheMap.entrySet()) 
  37. { SoftReference<Bitmap> sr = entry.getValue(); 
  38. if(null != sr) { 
  39. Bitmap bmp = sr.get(); 
  40. if(null != bmp) bmp.recycle(); 
  41. mCacheMap.clear(); 
  42. catch (Exception e) { 
  43. e.printStackTrace();} 
2、FileCache

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

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

3、编写异步加载组件AsyncImageLoader

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

  1. public class AsyncImageLoader{ 
  2. private MemoryCache mMemoryCache;//内存缓存 
  3. private FileCache mFileCache;//文件缓存 
  4. private ExecutorService mExecutorService;//线程池 
  5. //记录已经加载图片的ImageView 
  6. private Map<ImageView, String> mImageViews = Collections 
  7. .synchronizedMap(new WeakHashMap<ImageView, String>()); 
  8. //保存正在加载图片的url 
  9. private List<LoadPhotoTask> mTaskQueue = new ArrayList<LoadPhotoTask>(); 
  10. /** 
  11. * 默认采用一个大小为5的线程池 
  12. * @param context 
  13. * @param memoryCache 所采用的高速缓存 
  14. * @param fileCache 所采用的文件缓存 
  15. */ 
  16. public AsyncImageLoader(Context context, MemoryCache memoryCache, FileCache fileCache) { 
  17. mMemoryCache = memoryCache; 
  18. mFileCache = fileCache; 
  19. mExecutorService = Executors.newFixedThreadPool(5);//建立一个容量为5的固定尺寸的线程池(***正在运行的线程数量) 
  20. /** 
  21. * 根据url加载相应的图片 
  22. * @param url 
  23. * @return 先从一级缓存中取图片有则直接返回,如果没有则异步从文件(二级缓存)中取,如果没有再从网络端获取 
  24. */ 
  25. public Bitmap loadBitmap(ImageView imageView, String url) { 
  26. //先将ImageView记录到Map中,表示该ui已经执行过图片加载了 
  27. mImageViews.put(imageView, url); 
  28. Bitmap bitmap = mMemoryCache.get(url);//先从一级缓存中获取图片 
  29. if(bitmap == null) { 
  30. enquequeLoadPhoto(url, imageView);//再从二级缓存和网络中获取 
  31. return bitmap; 
  32.  
  33. /** 
  34. * 加入图片下载队列 
  35. * @param url 
  36. */ 
  37. private void enquequeLoadPhoto(String url, ImageView imageView) { 
  38. //如果任务已经存在,则不重新添加 
  39. if(isTaskExisted(url)) 
  40. return
  41. LoadPhotoTask task = new LoadPhotoTask(url, imageView); 
  42. synchronized (mTaskQueue) { 
  43. mTaskQueue.add(task);//将任务添加到队列中 
  44. mExecutorService.execute(task);//向线程池中提交任务,如果没有达到上限(5),则运行否则被阻塞 
  45.  
  46. /** 
  47. * 判断下载队列中是否已经存在该任务 
  48. * @param url 
  49. * @return 
  50. */ 
  51. private boolean isTaskExisted(String url) { 
  52. if(url == null
  53. return false
  54. synchronized (mTaskQueue) { 
  55. int size = mTaskQueue.size(); 
  56. for(int i=0; i<size; i++) { 
  57. LoadPhotoTask task = mTaskQueue.get(i); 
  58. if(task != null && task.getUrl().equals(url)) 
  59. return true
  60. return false
  61.  
  62. /** 
  63. * 从缓存文件或者网络端获取图片 
  64. * @param url 
  65. */ 
  66. private Bitmap getBitmapByUrl(String url) { 
  67. File f = mFileCache.getFile(url);//获得缓存图片路径 
  68. Bitmap b = ImageUtil.decodeFile(f);//获得文件的Bitmap信息 
  69. if (b != null)//不为空表示获得了缓存的文件 
  70. return b; 
  71. return ImageUtil.loadBitmapFromWeb(url, f);//同网络获得图片 
  72.  
  73. /** 
  74. * 判断该ImageView是否已经加载过图片了(可用于判断是否需要进行加载图片) 
  75. * @param imageView 
  76. * @param url 
  77. * @return 
  78. */ 
  79. private boolean imageViewReused(ImageView imageView, String url) { 
  80. String tag = mImageViews.get(imageView); 
  81. if (tag == null || !tag.equals(url)) 
  82. return true
  83. return false
  84.  
  85. private void removeTask(LoadPhotoTask task) { 
  86. synchronized (mTaskQueue) { 
  87. mTaskQueue.remove(task); 
  88.  
  89. class LoadPhotoTask implements Runnable { 
  90. private String url; 
  91. private ImageView imageView; 
  92. LoadPhotoTask(String url, ImageView imageView) { 
  93. this.url = url; 
  94. this.imageView = imageView; 
  95.  
  96. @Override 
  97. public void run() { 
  98. if (imageViewReused(imageView, url)) {//判断ImageView是否已经被复用 
  99. removeTask(this);//如果已经被复用则删除任务 
  100. return
  101. Bitmap bmp = getBitmapByUrl(url);//从缓存文件或者网络端获取图片 
  102. mMemoryCache.put(url, bmp);// 将图片放入到一级缓存中 
  103. if (!imageViewReused(imageView, url)) {//若ImageView未加图片则在ui线程中显示图片 
  104. BitmapDisplayer bd = new BitmapDisplayer(bmp, imageView, url); Activity a = (Activity) imageView.getContext(); 
  105. a.runOnUiThread(bd);//在UI线程调用bd组件的run方法,实现为ImageView控件加载图片 
  106. removeTask(this);//从队列中移除任务 
  107. public String getUrl() { 
  108. return url; 
  109.  
  110. /** 
  111. * 
  112. *由UI线程中执行该组件的run方法 
  113. */ 
  114. class BitmapDisplayer implements Runnable { 
  115. private Bitmap bitmap; 
  116. private ImageView imageView; 
  117. private String url; 
  118. public BitmapDisplayer(Bitmap b, ImageView imageView, String url) { 
  119. bitmap = b; 
  120. this.imageView = imageView; 
  121. this.url = url; 
  122. public void run() { 
  123. if (imageViewReused(imageView, url)) 
  124. return
  125. if (bitmap != null
  126. imageView.setImageBitmap(bitmap); 
  127.  
  128. /** 
  129. * 释放资源 
  130. */ 
  131. public void destroy() { 
  132. mMemoryCache.clear(); 
  133. mMemoryCache = null
  134. mImageViews.clear(); 
  135. mImageViews = null
  136. mTaskQueue.clear(); 
  137. mTaskQueue = null
  138. mExecutorService.shutdown(); 
  139. mExecutorService = null

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

4、工具类ImageUtil

  1. public class ImageUtil { 
  2. /** 
  3. * 从网络获取图片,并缓存在指定的文件中 
  4. * @param url 图片url 
  5. * @param file 缓存文件 
  6. * @return 
  7. */ 
  8. public static Bitmap loadBitmapFromWeb(String url, File file) { 
  9. HttpURLConnection conn = null
  10. InputStream is = null
  11. OutputStream os = null
  12. try { 
  13. Bitmap bitmap = null
  14. URL imageUrl = new URL(url); 
  15. conn = (HttpURLConnection) imageUrl.openConnection(); 
  16. conn.setConnectTimeout(30000); 
  17. conn.setReadTimeout(30000); 
  18. conn.setInstanceFollowRedirects(true); 
  19. is = conn.getInputStream(); 
  20. os = new FileOutputStream(file); 
  21. copyStream(is, os);//将图片缓存到磁盘中 
  22. bitmap = decodeFile(file); 
  23. return bitmap; 
  24. catch (Exception ex) { 
  25. ex.printStackTrace(); 
  26. return null
  27. finally { 
  28. try { 
  29. if(os != null) os.close(); 
  30. if(is != null) is.close(); 
  31. if(conn != null) conn.disconnect(); 
  32. catch (IOException e) { } 
  33.  
  34. public static Bitmap decodeFile(File f) { 
  35. try { 
  36. return BitmapFactory.decodeStream(new FileInputStream(f), nullnull); 
  37. catch (Exception e) { } 
  38. return null
  39. private static void copyStream(InputStream is, OutputStream os) { 
  40. final int buffer_size = 1024
  41. try { 
  42. byte[] bytes = new byte[buffer_size]; 
  43. for (;;) { 
  44. int count = is.read(bytes, 0, buffer_size); 
  45. if (count == -1
  46. break
  47. os.write(bytes, 0, count); 
  48. catch (Exception ex) { 
  49. ex.printStackTrace(); 

四、测试应用

组件之间的时序图:

1、编写MainActivity

  1. public class MainActivity extends Activity { 
  2. ListView list; 
  3. ListViewAdapter adapter; 
  4. @Override 
  5. public void onCreate(Bundle savedInstanceState) { 
  6. super.onCreate(savedInstanceState); 
  7. setContentView(R.layout.main); 
  8. list=(ListView)findViewById(R.id.list); 
  9. adapter=new ListViewAdapter(this, mStrings); 
  10. list.setAdapter(adapter); 
  11. public void onDestroy(){ 
  12. list.setAdapter(null); 
  13. super.onDestroy(); 
  14. adapter.destroy(); 
  15. private String[] mStrings={ 
  16. "http://news.21-sun.com/UserFiles/x_Image/x_20150606083511_0.jpg"
  17. "http://news.21-sun.com/UserFiles/x_Image/x_20150606082847_0.jpg"
  18. …..}; 
  19. }

2、编写适配器

  1. public class ListViewAdapter extends BaseAdapter { 
  2. private Activity mActivity; 
  3. private String[] data; 
  4. private static LayoutInflater inflater=null
  5. private AsyncImageLoader imageLoader;//异步组件 
  6.  
  7. public ListViewAdapter(Activity mActivity, String[] d) { 
  8. this.mActivity=mActivity; 
  9. data=d; 
  10. inflater = (LayoutInflater)mActivity.getSystemService( 
  11. Context.LAYOUT_INFLATER_SERVICE); 
  12. MemoryCache mcache=new MemoryCache();//内存缓存 
  13. File sdCard = android.os.Environment.getExternalStorageDirectory();//获得SD卡 
  14. File cacheDir = new File(sdCard, "jereh_cache" );//缓存根目录 
  15. FileCache fcache=new FileCache(mActivity, cacheDir, "news_img");//文件缓存 
  16. imageLoader = new AsyncImageLoader(mActivity, mcache,fcache); 
  17. public int getCount() { 
  18. return data.length; 
  19. public Object getItem(int position) { 
  20. return position; 
  21. public long getItemId(int position) { 
  22. return position; 
  23.  
  24. public View getView(int position, View convertView, ViewGroup parent) { 
  25. ViewHolder vh=null
  26. if(convertView==null){ 
  27. convertView = inflater.inflate(R.layout.item, null); 
  28. vh=new ViewHolder(); 
  29. vh.tvTitle=(TextView)convertView.findViewById(R.id.text); 
  30. vh.ivImg=(ImageView)convertView.findViewById(R.id.image); 
  31. convertView.setTag(vh); 
  32. }else
  33. vh=(ViewHolder)convertView.getTag(); 
  34. vh.tvTitle.setText("标题信息测试———— "+position); 
  35. vh.ivImg.setTag(data[position]); 
  36. //异步加载图片,先从一级缓存、再二级缓存、***网络获取图片 
  37. Bitmap bmp = imageLoader.loadBitmap(vh.ivImg, data[position]); 
  38. if(bmp == null) { 
  39. vh.ivImg.setImageResource(R.drawable.default_big); 
  40. else { 
  41. vh.ivImg.setImageBitmap(bmp); 
  42. return convertView; 
  43. private class ViewHolder{ 
  44. TextView tvTitle; 
  45. ImageView ivImg; 
  46. public void destroy() { 
  47. imageLoader.destroy(); 
责任编辑:chenqingxiang 来源: 博客园
相关推荐

2013-06-27 11:16:27

Android异步加载

2009-06-18 15:24:35

Hibernate二级

2013-09-08 23:30:56

EF Code Fir架构设计MVC架构设计

2009-09-21 14:59:31

Hibernate二级

2009-09-24 11:04:56

Hibernate二级

2009-09-21 14:39:40

Hibernate二级

2009-09-21 13:31:10

Hibernate 3

2013-10-16 16:58:17

iOS优化缓存优化

2009-09-23 09:37:07

Hibernate缓存

2009-06-10 15:00:58

Hibernate二级配置

2017-11-08 14:34:20

图片fresco程序员

2009-08-13 18:12:12

Hibernate 3

2022-12-02 12:01:30

Spring缓存生命周期

2022-03-01 18:03:06

Spring缓存循环依赖

2022-01-12 07:48:19

缓存Spring 循环

2010-01-27 17:53:18

Android显示网络

2023-04-27 08:18:10

MyBatis缓存存储

2019-08-21 14:34:41

2011-08-09 10:05:57

TableView服务器图片

2015-08-25 10:28:38

前端图片延迟加载
点赞
收藏

51CTO技术栈公众号