RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
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> mCacheMap = 
  6. new LinkedHashMap>() { 
  7. private static final long serialVersionUID = 1L; 
  8. //当缓存数量超过规定大小(返回true)会清除最早放入缓存的 
  9. protected boolean removeEldestEntry( 
  10. Map.Entry> 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 ref = mCacheMap.get(id); 
  22. return ref.get(); 
  23. } 
  24.  
  25. /** 
  26. * 将图片加入缓存 
  27. * @param id 
  28. * @param bitmap 
  29. */ 
  30. public void put(String id, Bitmap bitmap){ 
  31. mCacheMap.put(id, new SoftReference(bitmap)); 
  32. } 
  33. /** 
  34. * 清除所有缓存 
  35. */ 
  36. public void clear() { 
  37. try { 
  38. for(Map.Entry>entry :mCacheMap.entrySet()) 
  39. { SoftReference sr = entry.getValue(); 
  40. if(null != sr) { 
  41. Bitmap bmp = sr.get(); 
  42. if(null != bmp) bmp.recycle(); 
  43. } 
  44. } 
  45. mCacheMap.clear(); 
  46. } catch (Exception e) { 
  47. e.printStackTrace();} 
  48. } 
  49. } 
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. } 
  16. public File getFile(String url){ 
  17. File f=null; 
  18. try { 
  19. //对url进行编辑,解决中文路径问题 
  20. String filename = URLEncoder.encode(url,"utf-8"); 
  21. f = new File(mCacheDir, filename); 
  22. } catch (UnsupportedEncodingException e) { 
  23. e.printStackTrace(); 
  24. } 
  25. return f; 
  26. } 
  27. public void clear(){//清除缓存文件 
  28. File[] files = mCacheDir.listFiles(); 
  29. for(File f:files)f.delete(); 
  30. } 
  31. } 

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

编写完成之后,对于异步任务的执行只需调用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. } 
  35.  
  36. public static Bitmap decodeFile(File f) { 
  37. try { 
  38. return BitmapFactory.decodeStream(new FileInputStream(f), null, null); 
  39. } catch (Exception e) { } 
  40. return null; 
  41. } 
  42. private static void copyStream(InputStream is, OutputStream os) { 
  43. final int buffer_size = 1024; 
  44. try { 
  45. byte[] bytes = new byte[buffer_size]; 
  46. for (;;) { 
  47. int count = is.read(bytes, 0, buffer_size); 
  48. if (count == -1) 
  49. break; 
  50. os.write(bytes, 0, count); 
  51. } 
  52. } catch (Exception ex) { 
  53. ex.printStackTrace(); 
  54. } 
  55. } 
  56. } 

四、测试应用

组件之间的时序图:

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. } 
  12. public void onDestroy(){ 
  13. list.setAdapter(null); 
  14. super.onDestroy(); 
  15. adapter.destroy(); 
  16. } 
  17. private String[] mStrings={ 
  18. "http://news.21-sun.com/UserFiles/x_Image/x_20150606083511_0.jpg", 
  19. "http://news.21-sun.com/UserFiles/x_Image/x_20150606082847_0.jpg", 
  20. …..}; 
  21. }

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. } 
  18. public int getCount() { 
  19. return data.length; 
  20. } 
  21. public Object getItem(int position) { 
  22. return position; 
  23. } 
  24. public long getItemId(int position) { 
  25. return position; 
  26. } 
  27.  
  28. public View getView(int position, View convertView, ViewGroup parent) { 
  29. ViewHolder vh=null; 
  30. if(convertView==null){ 
  31. convertView = inflater.inflate(R.layout.item, null); 
  32. vh=new ViewHolder(); 
  33. vh.tvTitle=(TextView)convertView.findViewById(R.id.text); 
  34. vh.ivImg=(ImageView)convertView.findViewById(R.id.image); 
  35. convertView.setTag(vh); 
  36. }else{ 
  37. vh=(ViewHolder)convertView.getTag(); 
  38. } 
  39. vh.tvTitle.setText("标题信息测试———— "+position); 
  40. vh.ivImg.setTag(data[position]); 
  41. //异步加载图片,先从一级缓存、再二级缓存、***网络获取图片 
  42. Bitmap bmp = imageLoader.loadBitmap(vh.ivImg, data[position]); 
  43. if(bmp == null) { 
  44. vh.ivImg.setImageResource(R.drawable.default_big); 
  45. } else { 
  46. vh.ivImg.setImageBitmap(bmp); 
  47. } 
  48. return convertView; 
  49. } 
  50. private class ViewHolder{ 
  51. TextView tvTitle; 
  52. ImageView ivImg; 
  53. } 
  54. public void destroy() { 
  55. imageLoader.destroy(); 
  56. } 
  57. } 

分享文章:Android图片加载:采用二级缓存、异步加载网络图片
网页URL:http://www.zcwtytd.com/article/dhgcope.html