点击下载源代码

想起刚開始写代码的时候,领导叫我写一个头像下载的方法,当时屁颠屁颠就写了一个图片下载的,每次都要去网络上请求,最后直接被pass掉了

当时的思路是这种

后来渐渐地就知道了有二级缓存这东西。

自己也阅读过非常多关于双缓存的文章。

APP开发到越后面。对性能的要求越高。那么双缓存的优势就逐渐体现出来了。

所谓图片双缓存。首先到执行内存中请求,再到sd卡请求,最后到网络请求,流程图例如以下

那我们从第一部開始解析

1.先看 内存缓存的代码

[java] view
plain
copy

  1. public class MemoryCache implements ImageCache {
  2. private static final String TAG = MemoryCache.class.getSimpleName();
  3. private LruCache<String,Bitmap> mMemoryCache;
  4. public MemoryCache(){
  5. init();
  6. }
  7. private void init(){
  8. final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
  9. final int cacheSize = maxMemory/4;
  10. mMemoryCache = new LruCache<String,Bitmap>(cacheSize){
  11. @Override
  12. protected int sizeOf(String key, Bitmap value) {
  13. return value.getRowBytes()*value.getHeight()/1024;
  14. }
  15. };
  16. }
  17. @Override
  18. public Bitmap get(String key) {
  19. Bitmap bitmap = mMemoryCache.get(key);
  20. if (bitmap!=null){
  21. Log.i(TAG,"File is exist in memory");
  22. }
  23. return mMemoryCache.get(key);
  24. }
  25. @Override
  26. public void put(String key, Bitmap bitmap) {
  27. if (get(key)==null) {
  28. mMemoryCache.put(key, bitmap);
  29. }
  30. }
  31. }
[java] view
plain
copy

  1. private void init()

init()方法中对一些变量进行初始化,mMemoryCache用于在内存中缓存图片

[java] view
plain
copy

  1. public Bitmap get(String key) {}

get()方法用于从内存中获得缓存

[java] view
plain
copy

  1. public void put(String key, Bitmap bitmap) {}

put()方法将下载好的图片缓存到内存中,方便下次使用

2.再看sd卡缓存

[java] view
plain
copy

  1. public class DiskCache implements ImageCache {
  2. private static final String TAG = DiskCache.class.getSimpleName();
  3. static String mPath ;
  4. public DiskCache(Context context){
  5. init(context);
  6. }
  7. private void init(Context context){
  8. // 获取图片缓存路径
  9. mPath = getDiskCachePath(context,"bitmap");
  10. File cacheDir = new File(mPath);
  11. if (!cacheDir.exists()) {
  12. cacheDir.mkdirs();
  13. }
  14. }
  15. @Override
  16. public Bitmap get(String key) {
  17. File file = new File(mPath+key);
  18. if (file.exists()){
  19. return BitmapFactory.decodeFile(mPath+key);
  20. }
  21. return null;
  22. }
  23. @Override
  24. public void put(String key, Bitmap bitmap) {
  25. FileOutputStream fileOutputStream = null;
  26. try {
  27. File file = new File(mPath+key);
  28. if (file.exists()){
  29. Log.i(TAG,"File is exist on disk");
  30. }
  31. fileOutputStream = new FileOutputStream(mPath+key);
  32. bitmap.compress(Bitmap.CompressFormat.PNG,100,fileOutputStream);
  33. } catch (FileNotFoundException e) {
  34. e.printStackTrace();
  35. }finally {
  36. CloseUtils.closeQuietly(fileOutputStream);
  37. }
  38. }
  39. /**
  40. * 依据传入的dir获得路径
  41. * @param context
  42. * @param dir
  43. * @return
  44. */
  45. public String getDiskCachePath(Context context, String dir) {
  46. String cachePath;
  47. if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
  48. || !Environment.isExternalStorageRemovable()) {
  49. cachePath = context.getExternalCacheDir().getPath();
  50. } else {
  51. cachePath = context.getCacheDir().getPath();
  52. }
  53. return cachePath + File.separator + dir;
  54. }
  55. }

相同

[java] view
plain
copy

  1. private void init()

init()方法中对一些变量进行初始化,mMemoryCache用于在内存中缓存图片

[java] view
plain
copy

  1. public Bitmap get(String key) {}

get()方法用于从内存中获得缓存

[java] view
plain
copy

  1. public void put(String key, Bitmap bitmap) {}

put()方法将下载好的图片缓存到内存中,方便下次使用

接下来我们会在一个叫DoubleCache的类中对以上两种缓存方式进行管理

[java] view
plain
copy

  1. public class DoubleCache implements ImageCache {
  2. private static final String TAG = DoubleCache.class.getSimpleName();
  3. private MemoryCache mMemoryCache = null;
  4. private DiskCache mDiskCache = null;
  5. public DoubleCache(Context context){
  6. mMemoryCache = new MemoryCache();
  7. mDiskCache = new DiskCache(context);
  8. }
  9. @Override
  10. public Bitmap get(String url) {
  11. String key = url2Key(url);
  12. Bitmap bitmap = mMemoryCache.get(key);
  13. if(bitmap==null){
  14. bitmap = mDiskCache.get(key);
  15. }else {
  16. }
  17. return bitmap;
  18. }
  19. @Override
  20. public void put(String url, Bitmap bitmap) {
  21. String key = url2Key(url);
  22. mMemoryCache.put(key,bitmap);
  23. mDiskCache.put(key,bitmap);
  24. }
  25. //url转key
  26. private String url2Key(String url){
  27. String key = MD5.hashKeyForDisk(url)+".jpg";
  28. return key;
  29. }
  30. }

我们在获取缓存的时候先从内存中获取。当内存中击中直接返回,当内存中没有击中,则訪问sd卡。

3.看到这里,小伙伴们一定急了,这仅仅有从缓存中和sd卡中取图片,并没有从网络获取,别急。立即就来

[java] view
plain
copy

  1. public class ImageLoader {
  2. private static final String TAG = ImageLoader.class.getSimpleName();
  3. private static ImageLoader sInstance;
  4. private DoubleCache mDoubleCache = null;
  5. private ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
  6. private ImageLoader(Context context) {
  7. mDoubleCache = new DoubleCache(context);
  8. }
  9. public static ImageLoader getInstance(Context context) {
  10. if (sInstance == null) {
  11. synchronized (ImageLoader.class) {
  12. sInstance = new ImageLoader(context);
  13. }
  14. }
  15. return sInstance;
  16. }
  17. public void displayImage(String url, ImageView imageView) {
  18. Bitmap bitmap = mDoubleCache.get(url);
  19. if (bitmap != null) {
  20. imageView.setImageBitmap(bitmap);
  21. mDoubleCache.put(url,bitmap);
  22. return;
  23. }
  24. submitLoadRequest(url, imageView);
  25. }
  26. private void submitLoadRequest(final String url, final ImageView imageView) {
  27. Log.i(TAG,"Download,url:"+url);
  28. imageView.setTag(url);
  29. mExecutorService.submit(new Runnable() {
  30. @Override
  31. public void run() {
  32. final Bitmap bitmap = downloadImage(url);
  33. if (imageView.getTag().equals(url)) {
  34. imageView.post(new Runnable() {
  35. @Override
  36. public void run() {
  37. imageView.setImageBitmap(bitmap);
  38. }
  39. });
  40. }
  41. mDoubleCache.put(url, bitmap);
  42. }
  43. });
  44. }
  45. Handler handler = new Handler(){
  46. @Override
  47. public void handleMessage(Message msg) {
  48. }
  49. };
  50. public Bitmap downloadImage(String url) {
  51. Bitmap bitmap = null;
  52. HttpURLConnection conn = null;
  53. try {
  54. URL url1 = new URL(url);
  55. conn = (HttpURLConnection) url1.openConnection();
  56. bitmap = BitmapFactory.decodeStream(conn.getInputStream());
  57. if (bitmap!=null){
  58. mDoubleCache.put(url,bitmap);
  59. }
  60. } catch (MalformedURLException e) {
  61. e.printStackTrace();
  62. } catch (Exception e) {
  63. e.printStackTrace();
  64. } finally {
  65. if (conn != null) {
  66. conn.disconnect();
  67. }
  68. }
  69. return bitmap;
  70. }

[java] view
plain
copy

  1. displayImage()

方法中能够看到。假设缓存中都没有才从网络中获取

[java] view
plain
copy

  1. public Bitmap downloadImage(String url) {}

下载完毕之后。把图片放到缓存中。

到这里,我们的第二张流程图就走完了。是不是非常easy。

我们在看一下是怎样使用的

[java] view
plain
copy

  1. private ImageView imageView;
  2. private ImageView imageView2;
  3. @Override
  4. protected void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.activity_main);
  7. imageView = (ImageView) findViewById(R.id.image);
  8. imageView2 = (ImageView) findViewById(R.id.image2);
  9. imageView.setOnClickListener(new View.OnClickListener() {
  10. @Override
  11. public void onClick(View v) {
  12. ImageLoader.getInstance(MainActivity.this).displayImage("http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg", imageView);
  13. }
  14. });
  15. imageView2.setOnClickListener(new View.OnClickListener() {
  16. @Override
  17. public void onClick(View v) {
  18. ImageLoader.getInstance(MainActivity.this).displayImage("http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg", imageView2);
  19. }
  20. });
  21. }

点击下载源代码

Android图片二级缓存的更多相关文章

  1. picasso_强大的Android图片下载缓存库

    tag: android pic skill date: 2016/07/09 title: picasso-强大的Android图片下载缓存库 [本文转载自:泡在网上的日子 参考:http://bl ...

  2. 毕加索的艺术——Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选

    毕加索的艺术--Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选 官网: http://square.github.i ...

  3. 【第五篇】Volley代码修改之图片二级缓存以及相关源码阅读(重写ImageLoader.ImageCache)

    前面http://www.cnblogs.com/androidsuperman/p/8a157b18ede85caa61ca5bc04bba43d0.html 有讲到使用LRU来处理缓存的,但是只是 ...

  4. picasso-强大的Android图片下载缓存库

    编辑推荐:稀土掘金,这是一个针对技术开发者的一个应用,你可以在掘金上获取最新最优质的技术干货,不仅仅是Android知识.前端.后端以至于产品和设计都有涉猎,想成为全栈工程师的朋友不要错过! pica ...

  5. Android 图片三级缓存之内存缓存(告别软引用(SoftRefrerence)和弱引用(WeakReference))

    因为之前项目同事使用了图片三级缓存,今天整理项目的时候发现同事还是使用了软引用(SoftRefrerence)和弱引用(WeakReference),来管理在内存中的缓存.看到这个我就感觉不对了.脑海 ...

  6. Android 图片三级缓存

    图片缓存的原理 实现图片缓存也不难,需要有相应的cache策略.这里采用 内存-文件-网络 三层cache机制,其中内存缓存包括强引用缓存和软引用缓存(SoftReference),其实网络不算cac ...

  7. android图片的缓存--节约内存提高程序效率

    如今android应用占内存一个比一个大,android程序的质量亟待提高. 这里简单说说网络图片的缓存,我这边就简单的说说思路 1:网络图片,无疑须要去下载图片,我们不须要每次都去下载. 维护一张表 ...

  8. 如何使用picasso 对Android图片下载缓存

    相比较其他,picasso的图片缓存更加简单一些,他只需要一行代码就可以表述:导入相关jar包 Picasso.with(context).load("图片路径").into(Im ...

  9. Android图片载入缓存框架Glide

    Glide开源框架是Google推荐的图片载入和缓框架,其在Github上的开源地址是:https://github.com/bumptech/glide 当然一个Google推荐的框架肯定就是Vol ...

随机推荐

  1. css/js(工作中遇到的问题)-5

    后端换行符处理 问题描述 // Windows new line support (CR+LF, \r\n) str = str.replace(/\r\n/g, "\n"); 遍 ...

  2. js模板引擎-art-template常用

    art-template javascript 模板引擎 分为原生语法和简洁语法,本文主要是讲简洁语法 基础数据渲染 输出HTML 流程控制 遍历 调用自定义函数方法 子模板引入 基础数据渲染 一.引 ...

  3. Microsoft office(2)多级标题的设置

    在Microsoft office中要达到下面的标题结构: 1.首先将文字准备好: 2.将“绪论”,“无线...介绍”等章节标题分别选中 :段落-->大纲级别-->1级 3.同样的,“研究 ...

  4. RTP/RTCP、TCP、UDP、RTMP、RTSP

    OSI中的层 功能 TCP/IP协议族 应用层 文件传输,电子邮件,文件服务,虚拟终端 TFTP,FTP,HTTP,SNMP,SMTP,DNS,RIP,Telnet 表示层 数据格式化,代码转换,数据 ...

  5. (转)Android项目重构之路:架构篇

    去年10月底换到了新公司,做移动研发组的负责人,刚开始接手android项目时,发现该项目真的是一团糟.首先是其架构,是按功能模块进行划分的,本来按模块划分也挺好的,可是,他却分得太细,总共分为了17 ...

  6. Geeks - Check whether a given graph is Bipartite or not 二分图检查

    检查一个图是否是二分图的算法 使用的是宽度搜索: 1 初始化一个颜色记录数组 2 利用queue宽度遍历图 3 从随意源点出发.染色0. 或1 4 遍历这点的邻接点.假设没有染色就染色与这个源点相反的 ...

  7. 小凡带你搭建本地的光盘yum源

    小凡带你搭建本地的光盘yum源 导读 当我们在使用Yum工具安装软件包时,我们会感觉非常简单,它解决了一定程度软件包的依赖关系.但是Yum工具默认提供的是一种在线安装的方式,它会从默认的网上地址来寻找 ...

  8. 转:ios的图片文件上传代码

    转自: https://gist.github.com/igaiga/1354221 @interface ImageUploader : NSObject { NSData *theImage; } ...

  9. elastic不错的官方文档(中文)

    https://www.blog-china.cn/template/documentHtml/1484101683485.html http://www.open-open.com/doc/list ...

  10. 如何使用angularjs实现文本框设置值

    <!DOCTYPE html> <html ng-app="myApp"> <head> <title>angularjs-setV ...