picasso是Square公司开源的一个Android图形缓存库,地址http://square.github.io/picasso/,可以实现图片下载和缓存功能。

picasso使用简单,如下

  1. Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

主要有以下一些特性:

  • 在adapter中回收和取消当前的下载;
  • 使用最少的内存完成复杂的图形转换操作;
  • 自动的内存和硬盘缓存;
  • 图形转换操作,如变换大小,旋转等,提供了接口来让用户可以自定义转换操作;
  • 加载载网络或本地资源;

代码分析

Cache,缓存类



Lrucacha,主要是get和set方法,存储的结构采用了LinkedHashMap,这种map内部实现了lru算法(Least Recently Used 近期最少使用算法)。

  1. this.map = new LinkedHashMap<String, Bitmap>(0, 0.75f, true);

最后一个参数的解释:

true if the ordering should be done based on the last access (from least-recently accessed to most-recently accessed), and false if the ordering should be the order in which the entries were inserted.
因为可能会涉及多线程,所以在存取的时候都会加锁。而且每次set操作后都会判断当前缓存区是否已满,如果满了就清掉最少使用的图形。代码如下

  1. private void trimToSize(int maxSize) {
  2. while (true) {
  3. String key;
  4. Bitmap value;
  5. synchronized (this) {
  6. if (size < 0 || (map.isEmpty() && size != 0)) {
  7. throw new IllegalStateException(getClass().getName()
  8. + ".sizeOf() is reporting inconsistent results!");
  9. }
  10. if (size <= maxSize || map.isEmpty()) {
  11. break;
  12. }
  13. Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator()
  14. .next();
  15. key = toEvict.getKey();
  16. value = toEvict.getValue();
  17. map.remove(key);
  18. size -= Utils.getBitmapBytes(value);
  19. evictionCount++;
  20. }
  21. }
  22. }

Request,操作封装类



所有对图形的操作都会记录在这里,供之后图形的创建使用,如重新计算大小,旋转角度,也可以自定义变换,只需要实现Transformation,一个bitmap转换的接口。
  1. public interface Transformation {
  2. /**
  3. * Transform the source bitmap into a new bitmap. If you create a new bitmap instance, you must
  4. * call {@link android.graphics.Bitmap#recycle()} on {@code source}. You may return the original
  5. * if no transformation is required.
  6. */
  7. Bitmap transform(Bitmap source);
  8. /**
  9. * Returns a unique key for the transformation, used for caching purposes. If the transformation
  10. * has parameters (e.g. size, scale factor, etc) then these should be part of the key.
  11. */
  12. String key();
  13. }

当操作封装好以后,会将Request传到另一个结构中Action。

Action

Action代表了一个具体的加载任务,主要用于图片加载后的结果回调,有两个抽象方法,complete和error,也就是当图片解析为bitmap后用户希望做什么。最简单的就是将bitmap设置给imageview,失败了就将错误通过回调通知到上层。


ImageViewAction实现了Action,在complete中将bitmap和imageview组成了一个PicassoDrawable,里面会实现淡出的动画效果。

  1. @Override
  2. public void complete(Bitmap result, Picasso.LoadedFrom from) {
  3. if (result == null) {
  4. throw new AssertionError(String.format(
  5. "Attempted to complete action with no result!\n%s", this));
  6. }
  7. ImageView target = this.target.get();
  8. if (target == null) {
  9. return;
  10. }
  11. Context context = picasso.context;
  12. boolean debugging = picasso.debugging;
  13. PicassoDrawable.setBitmap(target, context, result, from, noFade,
  14. debugging);
  15. if (callback != null) {
  16. callback.onSuccess();
  17. }
  18. }

有了加载任务,具体的图片下载与解析是在哪里呢?这些都是耗时的操作,应该放在异步线程中进行,就是下面的BitmapHunter。

BitmapHunter


BitmapHunter是一个Runnable,其中有一个decode的抽象方法,用于子类实现不同类型资源的解析。

  1. @Override
  2. public void run() {
  3. try {
  4. Thread.currentThread()
  5. .setName(Utils.THREAD_PREFIX + data.getName());
  6. result = hunt();
  7. if (result == null) {
  8. dispatcher.dispatchFailed(this);
  9. } else {
  10. dispatcher.dispatchComplete(this);
  11. }
  12. } catch (IOException e) {
  13. exception = e;
  14. dispatcher.dispatchRetry(this);
  15. } catch (Exception e) {
  16. exception = e;
  17. dispatcher.dispatchFailed(this);
  18. } finally {
  19. Thread.currentThread().setName(Utils.THREAD_IDLE_NAME);
  20. }
  21. }
  22. abstract Bitmap decode(Request data) throws IOException;
  23. Bitmap hunt() throws IOException {
  24. Bitmap bitmap;
  25. if (!skipMemoryCache) {
  26. bitmap = cache.get(key);
  27. if (bitmap != null) {
  28. stats.dispatchCacheHit();
  29. loadedFrom = MEMORY;
  30. return bitmap;
  31. }
  32. }
  33. bitmap = decode(data);
  34. if (bitmap != null) {
  35. stats.dispatchBitmapDecoded(bitmap);
  36. if (data.needsTransformation() || exifRotation != 0) {
  37. synchronized (DECODE_LOCK) {
  38. if (data.needsMatrixTransform() || exifRotation != 0) {
  39. bitmap = transformResult(data, bitmap, exifRotation);
  40. }
  41. if (data.hasCustomTransformations()) {
  42. bitmap = applyCustomTransformations(
  43. data.transformations, bitmap);
  44. }
  45. }
  46. stats.dispatchBitmapTransformed(bitmap);
  47. }
  48. }
  49. return bitmap;
  50. }

可以看到,在decode生成原始bitmap,之后会做需要的转换transformResult和applyCustomTransformations。最后在将最终的结果传递到上层dispatcher.dispatchComplete(this)。

基本的组成元素有了,那这一切是怎么连接起来运行呢,答案是Dispatcher。

Dispatcher任务调度器

在bitmaphunter成功得到bitmap后,就是通过dispatcher将结果传递出去的,当然让bitmaphunter执行也要通过Dispatcher。

Dispatcher内有一个HandlerThread,所有的请求都会通过这个thread转换,也就是请求也是异步的,这样应该是为了Ui线程更加流畅,同时保证请求的顺序,因为handler的消息队列。

外部调用的是dispatchXXX方法,然后通过handler将请求转换到对应的performXXX方法。

例如生成Action以后就会调用dispather的dispatchSubmit()来请求执行,

  1. void dispatchSubmit(Action action) {
  2. handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
  3. }

handler接到消息后转换到performSubmit方法

  1. void performSubmit(Action action) {
  2. BitmapHunter hunter = hunterMap.get(action.getKey());
  3. if (hunter != null) {
  4. hunter.attach(action);
  5. return;
  6. }
  7. if (service.isShutdown()) {
  8. return;
  9. }
  10. hunter = forRequest(context, action.getPicasso(), this, cache, stats,
  11. action, downloader);
  12. hunter.future = service.submit(hunter);
  13. hunterMap.put(action.getKey(), hunter);
  14. }

这里将通过action得到具体的BitmapHunder,然后交给ExecutorService执行。

下面是Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView)的过程,
  1. public static Picasso with(Context context) {
  2. if (singleton == null) {
  3. singleton = new Builder(context).build();
  4. }
  5. return singleton;
  6. }
  7. public Picasso build() {
  8. Context context = this.context;
  9. if (downloader == null) {
  10. downloader = Utils.createDefaultDownloader(context);
  11. }
  12. if (cache == null) {
  13. cache = new LruCache(context);
  14. }
  15. if (service == null) {
  16. service = new PicassoExecutorService();
  17. }
  18. if (transformer == null) {
  19. transformer = RequestTransformer.IDENTITY;
  20. }
  21. Stats stats = new Stats(cache);
  22. Dispatcher dispatcher = new Dispatcher(context, service, HANDLER,
  23. downloader, cache, stats);
  24. return new Picasso(context, dispatcher, cache, listener,
  25. transformer, stats, debugging);
  26. }

在Picasso.with()的时候会将执行所需的所有必备元素创建出来,如缓存cache、执行executorService、调度dispatch等,在load()时创建Request,在into()中创建action、bitmapHunter,并最终交给dispatcher执行。

picasso图片缓存框架的更多相关文章

  1. Android图片缓存框架Glide

    Android图片缓存框架Glide Glide是Google提供的一个组件.它具有获取.解码和展示视频剧照.图片.动画等功能.它提供了灵活的API,帮助开发者将Glide应用在几乎任何网络协议栈中. ...

  2. android图片缓存框架Android-Universal-Image-Loader

    http://blog.csdn.net/king_is_everyone/article/details/34107081 最近跟同学们做了一个创业项目,其实跟以前做项目不同,以前大多数都是做web ...

  3. iOS图片缓存框架SDWebImage

    本文转发至: http://blog.csdn.net/uxyheaven/article/details/7909373 http://www.cocoachina.com/ios/20141212 ...

  4. android图片缓存框架Android-Universal-Image-Loader(二)

    http://blog.csdn.net/king_is_everyone/article/details/35595515 这篇打算直接告诉大家怎么用吧,其实这个也不是很难的框架,大致使用过程如下: ...

  5. 通过案例快速学会Picasso图片缓存库

    picasso是Square公司开源的一个Android图形缓存库,官网地址http://square.github.io/picasso/,可以实现图片下载和缓存功能.        下载地址:ht ...

  6. Android图片缓存之初识Glide

    前言: 前面总结学习了图片的使用以及Lru算法,今天来学习一下比较优秀的图片缓存开源框架.技术本身就要不断的更迭,从最初的自己使用SoftReference实现自己的图片缓存,到后来做电商项目自己的实 ...

  7. 安卓高级 Android图片缓存之初识Glide

    前言: 前面总结学习了图片的使用以及Lru算法,今天来学习一下比较优秀的图片缓存开源框架.技术本身就要不断的更迭,从最初的自己使用SoftReference实现自己的图片缓存,到后来做电商项目自己的实 ...

  8. Android图片缓存之初识Glide(三)

    前言: 前面总结学习了图片的使用以及Lru算法,今天来学习一下比较优秀的图片缓存开源框架.技术本身就要不断的更迭,从最初的自己使用SoftReference实现自己的图片缓存,到后来做电商项目自己的实 ...

  9. Android图片缓存之Bitmap详解

    前言: 最近准备研究一下图片缓存框架,基于这个想法觉得还是先了解有关图片缓存的基础知识,今天重点学习一下Bitmap.BitmapFactory这两个类. 图片缓存相关博客地址: Android图片缓 ...

随机推荐

  1. bzoj1071[SCOI2007]组队

    1071: [SCOI2007]组队 Time Limit: 3 Sec  Memory Limit: 128 MBSubmit: 2472  Solved: 792[Submit][Status][ ...

  2. hdu5634 BestCoder Round #73 (div.1)

    Rikka with Phi  Accepts: 5  Submissions: 66  Time Limit: 16000/8000 MS (Java/Others)  Memory Limit: ...

  3. JavaBean实现用户登陆

    本文简单讲述使用javabean实现用户登录,包括用户登录,注册和退出等. 系统结构图 2.数据库表 create table P_USER ( id       VARCHAR2(50) not n ...

  4. PTA 邻接表存储图的广度优先遍历(20 分)

    6-2 邻接表存储图的广度优先遍历(20 分) 试实现邻接表存储图的广度优先遍历. 函数接口定义: void BFS ( LGraph Graph, Vertex S, void (*Visit)(V ...

  5. @Transient 理解

    transient使用小结 1)一旦变量被transient修饰,变量将不再是对象持久化的一部分,该变量内容在序列化后无法获得访问. 2)transient关键字只能修饰变量,而不能修饰方法和类.注意 ...

  6. windows下cmd中命令操作

    windows下cmd中命令:   cls清空 上下箭头进行命令历史命令切换 ------------------------------------------------------------- ...

  7. scratch写的图灵机

    大多数人对于scratch不感冒,因为觉得这是孩子玩的.的确,积木的方式不适合专业程序员写代码,然而别小看scratch,怎么说,它也是图灵完备的.而且,过程支持递归,虽然带不了返回值. 虽然计算速度 ...

  8. PHP MySQL 创建数据表

    PHP 创建 MySQL 表 一个数据表有一个唯一名称,并有行和列组成. 使用 MySQLi 和 PDO 创建 MySQL 表 CREATE TABLE 语句用于创建 MySQL 表. 我们将创建一个 ...

  9. 详解BLE 空中包格式—兼BLE Link layer协议解析

    BLE有几种空中包格式?常见的PDU命令有哪些?PDU和MTU的区别是什么?DLE又是什么?BLE怎么实现重传的?BLE ACK机制原理是什么?希望这篇文章能帮你回答以上问题. 虽然BLE空中包(pa ...

  10. AbstractQueuedSynchronizer源码解读

    1. 背景 AQS(java.util.concurrent.locks.AbstractQueuedSynchronizer)是Doug Lea大师创作的用来构建锁或者其他同步组件(信号量.事件等) ...