Android圖片下載緩存庫picasso解析

http://blog.csdn.net/xu_fu/article/details/17043231


picasso是Square公司開源的一個Android圖形緩存庫,地址http://square.github.io/picasso/,可以實現圖片下載和緩存功能。

picasso使用簡單,如下

[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);  

主要有以下一些特性:

  • 在adapter中回收和取消當前的下載;
  • 使用最少的內存完成複雜的圖形轉換操作;
  • 自動的內存和硬盤緩存;
  • 圖形轉換操作,如變換大小,旋轉等,提供了接口來讓用戶可以自定義轉換操作;
  • 加載載網絡或本地資源;

代碼分析

Cache,緩存類



Lrucacha,主要是get和set方法,存儲的結構採用了LinkedHashMap,這種map內部實現了lru算法(Least Recently Used 近期最少使用算法)。
[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. this.map = new LinkedHashMap<String, Bitmap>(00.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操作後都會判斷當前緩存區是否已滿,如果滿了就清掉最少使用的圖形。代碼如下
[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  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.   
  11.                 if (size <= maxSize || map.isEmpty()) {  
  12.                     break;  
  13.                 }  
  14.   
  15.                 Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator()  
  16.                         .next();  
  17.                 key = toEvict.getKey();  
  18.                 value = toEvict.getValue();  
  19.                 map.remove(key);  
  20.                 size -= Utils.getBitmapBytes(value);  
  21.                 evictionCount++;  
  22.             }  
  23.         }  
  24. }  

Request,操作封裝類



所有對圖形的操作都會記錄在這裏,供之後圖形的創建使用,如重新計算大小,旋轉角度,也可以自定義變換,只需要實現Transformation,一個bitmap轉換的接口。
[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  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.   /** 
  10.    * Returns a unique key for the transformation, used for caching purposes. If the transformation 
  11.    * has parameters (e.g. size, scale factor, etc) then these should be part of the key. 
  12.    */  
  13.   String key();  
  14. }  

當操作封裝好以後,會將Request傳到另一個結構中Action。

Action

Action代表了一個具體的加載任務,主要用於圖片加載後的結果回調,有兩個抽象方法,complete和error,也就是當圖片解析爲bitmap後用戶希望做什麼。最簡單的就是將bitmap設置給imageview,失敗了就將錯誤通過回調通知到上層。


ImageViewAction實現了Action,在complete中將bitmap和imageview組成了一個PicassoDrawable,裏面會實現淡出的動畫效果。
[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  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.   
  8.         ImageView target = this.target.get();  
  9.         if (target == null) {  
  10.             return;  
  11.         }  
  12.   
  13.         Context context = picasso.context;  
  14.         boolean debugging = picasso.debugging;  
  15.         PicassoDrawable.setBitmap(target, context, result, from, noFade,  
  16.                 debugging);  
  17.   
  18.         if (callback != null) {  
  19.             callback.onSuccess();  
  20.         }  
  21.     }  

有了加載任務,具體的圖片下載與解析是在哪裏呢?這些都是耗時的操作,應該放在異步線程中進行,就是下面的BitmapHunter。

BitmapHunter


BitmapHunter是一個Runnable,其中有一個decode的抽象方法,用於子類實現不同類型資源的解析。

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

可以看到,在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()來請求執行,
[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. void dispatchSubmit(Action action) {  
  2.         handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));  
  3.     }  

handler接到消息後轉換到performSubmit方法
[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. void performSubmit(Action action) {  
  2.         BitmapHunter hunter = hunterMap.get(action.getKey());  
  3.         if (hunter != null) {  
  4.             hunter.attach(action);  
  5.             return;  
  6.         }  
  7.   
  8.         if (service.isShutdown()) {  
  9.             return;  
  10.         }  
  11.   
  12.         hunter = forRequest(context, action.getPicasso(), this, cache, stats,  
  13.                 action, downloader);  
  14.         hunter.future = service.submit(hunter);  
  15.         hunterMap.put(action.getKey(), hunter);  
  16.     }  

這裏將通過action得到具體的BitmapHunder,然後交給ExecutorService執行。
下面是Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView)的過程,
[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. public static Picasso with(Context context) {  
  2.         if (singleton == null) {  
  3.             singleton = new Builder(context).build();  
  4.         }  
  5.         return singleton;  
  6.     }  
  7.       
  8.     public Picasso build() {  
  9.             Context context = this.context;  
  10.   
  11.             if (downloader == null) {  
  12.                 downloader = Utils.createDefaultDownloader(context);  
  13.             }  
  14.             if (cache == null) {  
  15.                 cache = new LruCache(context);  
  16.             }  
  17.             if (service == null) {  
  18.                 service = new PicassoExecutorService();  
  19.             }  
  20.             if (transformer == null) {  
  21.                 transformer = RequestTransformer.IDENTITY;  
  22.             }  
  23.   
  24.             Stats stats = new Stats(cache);  
  25.   
  26.             Dispatcher dispatcher = new Dispatcher(context, service, HANDLER,  
  27.                     downloader, cache, stats);  
  28.   
  29.             return new Picasso(context, dispatcher, cache, listener,  
  30.                     transformer, stats, debugging);  
  31.         }  

在Picasso.with()的時候會將執行所需的所有必備元素創建出來,如緩存cache、執行executorService、調度dispatch等,在load()時創建Request,在into()中創建action、bitmapHunter,並最終交給dispatcher執行。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章