Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Picasso 源碼深度解析:從入隊到顯示的完整鏈路

編輯:關於 Android 程式設計

Android 的圖片加載庫我用過不少:UIL、Volley、Picasso、Glide、Fresco,都是不錯的選擇。其中 Picasso 研究得稍多一些。網上關於它的源碼分析文章很多,但我還是覺得自己從頭跟一遍源碼,收穫才真正屬於自己,於是有了這篇記錄。至於使用教學,本文不涉及,稍後另寫一篇。

文章有點長,感興趣的朋友請耐心看完。

整體架構

Picasso 的核心類包括 Picasso、Dispatcher、BitmapHunter、RequestHandler、Request、Action、Cache 等。Picasso 類是負責圖片下載、變換與緩存的管理器:收到下載請求後創建 Request 並提交給 Dispatcher;Dispatcher 找到對應的 RequestHandler,把請求與處理器一起丟進線程池;圖片取回後,最終交給 PicassoDrawable 顯示到 Target 上。

創建 -> 入隊 -> 執行 -> 解碼 -> 變換 -> 批處理 -> 完成 -> 分發 -> 顯示(可選)

源碼分析

先看最簡單的用法:

Picasso.with(this).load("url").into(imageView);

with() 方法

Picasso 類是整個加載器的入口,負責初始化各模塊、配置參數,採用單例模式。

public static Picasso with(Context context) {
    if (singleton == null) {
        synchronized (Picasso.class) {
            if (singleton == null) {
                singleton = new Builder(context).build();
            }
        }
    }
    return singleton;
}

雙重檢查鎖維護單例,未實例化時通過 Builder 創建。接著看 Builder:

public Picasso build() {
    Context context = this.context;
    if (downloader == null) {
        downloader = Utils.createDefaultDownloader(context);
    }
    if (cache == null) {
        cache = new LruCache(context);
    }
    if (service == null) {
        service = new PicassoExecutorService();
    }
    if (transformer == null) {
        transformer = RequestTransformer.IDENTITY;
    }
    Stats stats = new Stats(cache);
    Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);
    return new Picasso(context, dispatcher, cache, listener, transformer,
            requestHandlers, stats, defaultBitmapConfig, indicatorsEnabled, loggingEnabled);
}

這裡完成了幾項預設配置:內存緩存基於 LruCache、磁盤緩存基於 HTTP 緩存(HttpResponseCache);創建預設下載器;創建含 3 條 worker 線程的線程池;創建不做任何處理、僅轉發請求的 Transformer;創建用於統計緩存命中率與下載時長的 Stats;準備處理不同加載請求的 RequestHandlers;最後構造 Picasso 實例。

Downloader

static Downloader createDefaultDownloader(Context context) {
    try {
        Class.forName("com.squareup.okhttp.OkHttpClient");
        return OkHttpLoaderCreator.create(context);
    } catch (ClassNotFoundException ignored) {
    }
    return new UrlConnectionDownloader(context);
}

先反射探測是否依賴 okhttp,有則用 OkHttpClient,否則退回預設的 HttpUrlConnection。順帶一提,從 4.4 開始 okhttp 已經是 HttpUrlConnection 的實現引擎了。

緩存目錄:

private static final String PICASSO_CACHE = "picasso-cache";

static File createDefaultCacheDir(Context context) {
    File cache = new File(context.getApplicationContext().getCacheDir(), PICASSO_CACHE);
    if (!cache.exists()) {
        cache.mkdirs();
    }
    return cache;
}

Cache

緩存採 LRU(最近最少使用)算法,容量取可用堆內存的約 15%(七分之一):

static int calculateMemoryCacheSize(Context context) {
    ActivityManager am = getService(context, ACTIVITY_SERVICE);
    boolean largeHeap = (context.getApplicationInfo().flags & FLAG_LARGE_HEAP) != 0;
    int memoryClass = am.getMemoryClass();
    if (largeHeap && SDK_INT >= HONEYCOMB) {
        memoryClass = ActivityManagerHoneycomb.getLargeMemoryClass(am);
    }
    // Target ~15% of the available heap.
    return 1024 * 1024 * memoryClass / 7;
}

ExecutorService

PicassoExecutorService 實現自帶的線程池,構造時實例化工作隊列與線程工廠,默認線程數為 3:

private static final int DEFAULT_THREAD_COUNT = 3;

同時會依網絡狀況动态调整——WiFi 4 條、4G 3 條、3G 2 條、2G 只留 1 條,靠 Dispatcher 中註冊的網絡變化廣播接收者觸發:

void adjustThreadCount(NetworkInfo info) {
    if (info == null || !info.isConnectedOrConnecting()) {
        setThreadCount(DEFAULT_THREAD_COUNT);
        return;
    }
    switch (info.getType()) {
        case ConnectivityManager.TYPE_WIFI:
        case ConnectivityManager.TYPE_WIMAX:
        case ConnectivityManager.TYPE_ETHERNET:
            setThreadCount(4);
            break;
        case ConnectivityManager.TYPE_MOBILE:
            switch (info.getSubtype()) {
                case TelephonyManager.NETWORK_TYPE_LTE: // 4G
                case TelephonyManager.NETWORK_TYPE_HSPAP:
                case TelephonyManager.NETWORK_TYPE_EHRPD:
                    setThreadCount(3);
                    break;
                case TelephonyManager.NETWORK_TYPE_UMTS: // 3G
                case TelephonyManager.NETWORK_TYPE_CDMA:
                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                case TelephonyManager.NETWORK_TYPE_EVDO_A:
                case TelephonyManager.NETWORK_TYPE_EVDO_B:
                    setThreadCount(2);
                    break;
                case TelephonyManager.NETWORK_TYPE_GPRS: // 2G
                case TelephonyManager.NETWORK_TYPE_EDGE:
                    setThreadCount(1);
                    break;
                default:
                    setThreadCount(DEFAULT_THREAD_COUNT);
            }
            break;
        default:
            setThreadCount(DEFAULT_THREAD_COUNT);
    }
}

RequestTransformer 與 Stats

Transformer 負責對 RequestCreator 產生的 Request 做轉換,默認實現甚麼都不做,直接放行。Stats 則記錄緩存命中數、未命中數、總大小、平均大小、下載次數等指標。

Dispatcher

每個 Dispatcher 都關聯線程池(service)、下載器(downloader)、主線程 Handler、緩存(cache)與監控器(stats):

Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);

Picasso 構造方法

構造方法中除了賦值與創建清理線程等對象,最重要的是初始化 requestHandlers:

int builtInHandlers = 7;
int extraCount = (extraRequestHandlers != null ? extraRequestHandlers.size() : 0);
List<RequestHandler> allRequestHandlers = new ArrayList<RequestHandler>(builtInHandlers + extraCount);
// ResourceRequestHandler 必須排在最前,避免其他 handler 對 request.uri 做 null 判斷
allRequestHandlers.add(new ResourceRequestHandler(context));
if (extraRequestHandlers != null) {
    allRequestHandlers.addAll(extraRequestHandlers);
}
allRequestHandlers.add(new ContactsPhotoRequestHandler(context));
allRequestHandlers.add(new MediaStoreRequestHandler(context));
allRequestHandlers.add(new ContentStreamRequestHandler(context));
allRequestHandlers.add(new AssetRequestHandler(context));
allRequestHandlers.add(new FileRequestHandler(context));
allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats));
requestHandlers = Collections.unmodifiableList(allRequestHandlers);

除了自定義的 extraRequestHandlers,內建了 7 個處理器,分別負責網絡、file、asset、聯繫人頭像、MediaStore、ContentStream 與資源 ID 等來源,用一個 ArrayList 依次存放。

load() 方法

load 支持四種入參:

public RequestCreator load(Uri uri) {
    return new RequestCreator(this, uri, 0);
}

public RequestCreator load(String path) {
    if (path == null) {
        return new RequestCreator(this, null, 0);
    }
    if (path.trim().length() == 0) {
        throw new IllegalArgumentException("Path must not be empty.");
    }
    return load(Uri.parse(path));
}

public RequestCreator load(File file) {
    if (file == null) {
        return new RequestCreator(this, null, 0);
    }
    return load(Uri.fromFile(file));
}

public RequestCreator load(int resourceId) {
    if (resourceId == 0) {
        throw new IllegalArgumentException("Resource ID must not be zero.");
    }
    return new RequestCreator(this, null, resourceId);
}

無論傳 String、Uri 還是 File,最終都返回一個 RequestCreator。再看它的構造:

RequestCreator(Picasso picasso, Uri uri, int resourceId) {
    if (picasso.shutdown) {
        throw new IllegalStateException(
                "Picasso instance already shut down. Cannot submit new requests.");
    }
    this.picasso = picasso;
    this.data = new Request.Builder(uri, resourceId, picasso.defaultBitmapConfig);
}

RequestCreator 封裝了一次請求,而請求在 Picasso 中被抽象為 Request。它提供了 placeholder、error、tag、fit、resize、centerCrop、centerInside、rotate、fetch、transform 等大量方法;由於可配置項實在太多,Request 本身也採用了 Builder 模式。

into() 方法

into 有多個重載,因為 Picasso 不僅能加載到 ImageView,還能加載到 Target 或 RemoteView。以 ImageView 版本為例:

public void into(ImageView target, Callback callback) {
    long started = System.nanoTime();
    checkMain();
    if (target == null) {
        throw new IllegalArgumentException("Target must not be null.");
    }
    if (!data.hasImage()) {
        // 沒有設置圖片,取消請求
        picasso.cancelRequest(target);
        if (setPlaceholder) {
            setPlaceholder(target, getPlaceholderDrawable());
        }
        return;
    }
    if (deferred) {
        if (data.hasSize()) {
            throw new IllegalStateException("Fit cannot be used with resize.");
        }
        // 需要適配 ImageView,先拿到它的尺寸
        int width = target.getWidth();
        int height = target.getHeight();
        if (width == 0 || height == 0) {
            if (setPlaceholder) {
                setPlaceholder(target, getPlaceholderDrawable());
            }
            picasso.defer(target, new DeferredRequestCreator(this, target, callback));
            return;
        }
        data.resize(width, height);
    }
    Request request = createRequest(started);
    String requestKey = createKey(request);
    if (shouldReadFromMemoryCache(memoryPolicy)) {
        Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
        if (bitmap != null) {
            picasso.cancelRequest(target);
            setBitmap(target, picasso.context, bitmap, MEMORY, noFade, picasso.indicatorsEnabled);
            if (picasso.loggingEnabled) {
                log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), "from " + MEMORY);
            }
            if (callback != null) {
                callback.onSuccess();
            }
            return;
        }
    }
    if (setPlaceholder) {
        setPlaceholder(target, getPlaceholderDrawable());
    }
    Action action = new ImageViewAction(picasso, target, request, memoryPolicy,
            networkPolicy, errorResId, errorDrawable, requestKey, tag, callback, noFade);
    picasso.enqueueAndSubmit(action);
}

流程很清楚:先查內存緩存,命中就直接顯示並回調;未命中則創建 Action 交給 Dispatcher。

picasso.enqueueAndSubmit

void enqueueAndSubmit(Action action) {
    Object target = action.getTarget();
    if (target != null && targetToAction.get(target) != action) {
        // 內部會檢查是否在主線程
        cancelExistingRequest(target);
        targetToAction.put(target, action);
    }
    submit(action);
}

void submit(Action action) {
    dispatcher.dispatchSubmit(action);
}

它先從 action 拿到 target(也就是 ImageView),在 weakHashMap 中查對應的舊 action;若與傳入的不同,就取消舊任務——這正是同一 ImageView 連續 load 時,前面請求被自動廢棄的原因。最後提交新任務。

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

這個 handler 是 DispatcherHandler:

this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);

而 dispatcherThread 是一個 HandlerThread,也就是說這些消息處理發生在子線程,不會阻塞主線程的消息隊列。收到 REQUEST_SUBMIT 後會調用 dispatcher.performSubmit(action)。

dispatcher.performSubmit

void performSubmit(Action action, boolean dismissFailed) {
    // 該 tag 的任務是否被暫停
    if (pausedTags.contains(action.getTag())) {
        pausedActions.put(action.getTarget(), action);
        return;
    }
    // 相同 key 的任務已存在,直接掛上去
    BitmapHunter hunter = hunterMap.get(action.getKey());
    if (hunter != null) {
        hunter.attach(action);
        return;
    }
    // 線程池已關閉
    if (service.isShutdown()) {
        return;
    }
    // 遍歷 requestHandlers,找到能處理本次請求的那一個
    hunter = forRequest(action.getPicasso(), this, cache, stats, action);
    // 提交執行,並拿到 future
    hunter.future = service.submit(hunter);
    hunterMap.put(action.getKey(), hunter);
    if (dismissFailed) {
        failedActions.remove(action.getTarget());
    }
}

forRequest 會依次調用各 RequestHandler 的 canHandleRequest(),找到合適的處理器後創建 BitmapHunter 並返回。隨後 service.submit(hunter) 啟動它——BitmapHunter 實現了 Runnable,因此 run() 會被執行。

BitmapHunter 的 run()

@Override
public void run() {
    try {
        updateThreadName(data);
        result = hunt();
        if (result == null) {
            dispatcher.dispatchFailed(this);
        } else {
            dispatcher.dispatchComplete(this);
        }
    } catch (Downloader.ResponseException e) {
        if (!e.localCacheOnly || e.responseCode != 504) {
            exception = e;
        }
        dispatcher.dispatchFailed(this);
    } catch (NetworkRequestHandler.ContentLengthException e) {
        exception = e;
        dispatcher.dispatchRetry(this);
    } catch (IOException e) {
        exception = e;
        dispatcher.dispatchRetry(this);
    } catch (OutOfMemoryError e) {
        StringWriter writer = new StringWriter();
        stats.createSnapshot().dump(new PrintWriter(writer));
        exception = new RuntimeException(writer.toString(), e);
        dispatcher.dispatchFailed(this);
    } catch (Exception e) {
        exception = e;
        dispatcher.dispatchFailed(this);
    } finally {
        Thread.currentThread().setName(Utils.THREAD_IDLE_NAME);
    }
}

一連串 catch 按類型分流異常:可重試的走 dispatchRetry,其餘走 dispatchFailed。核心邏輯在 hunt()。

hunt()

Bitmap hunt() throws IOException {
    Bitmap bitmap = null;
    // 仍然先查緩存
    if (shouldReadFromMemoryCache(memoryPolicy)) {
        bitmap = cache.get(key);
        if (bitmap != null) {
            stats.dispatchCacheHit();
            loadedFrom = MEMORY;
            return bitmap;
        }
    }
    // 緩存沒有,交給 requestHandler 加載
    data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
    RequestHandler.Result result = requestHandler.load(data, networkPolicy);
    if (result != null) {
        loadedFrom = result.getLoadedFrom();
        exifRotation = result.getExifOrientation();
        bitmap = result.getBitmap();
        // 若沒有直接給 bitmap,就從流中解碼
        if (bitmap == null) {
            InputStream is = result.getStream();
            try {
                bitmap = decodeStream(is, data);
            } finally {
                Utils.closeQuietly(is);
            }
        }
    }
    if (bitmap != null) {
        stats.dispatchBitmapDecoded(bitmap);
        if (data.needsTransformation() || exifRotation != 0) {
            // 全局鎖,保證同一時刻只有一張圖在做變換
            synchronized (DECODE_LOCK) {
                if (data.needsMatrixTransform() || exifRotation != 0) {
                    bitmap = transformResult(data, bitmap, exifRotation);
                }
                if (data.hasCustomTransformations()) {
                    bitmap = applyCustomTransformations(data.transformations, bitmap);
                }
            }
            if (bitmap != null) {
                stats.dispatchBitmapTransformed(bitmap);
            }
        }
    }
    return bitmap;
}

值得注意的有兩點:一是重試時第一次會以 OFFLINE 策略再查一次緩存;二是變換環節用 DECODE_LOCK 全局鎖串行化,避免同時處理多張大圖導致內存峰值。

RequestHandler 的 load()

以網絡請求的 NetworkRequestHandler 為例:

@Override
public Result load(Request request, int networkPolicy) throws IOException {
    Response response = downloader.load(request.uri, request.networkPolicy);
    if (response == null) {
        return null;
    }
    Picasso.LoadedFrom loadedFrom = response.cached ? DISK : NETWORK;
    Bitmap bitmap = response.getBitmap();
    if (bitmap != null) {
        return new Result(bitmap, loadedFrom);
    }
    InputStream is = response.getInputStream();
    if (is == null) {
        return null;
    }
    // 有時重放請求時 content-length 為 0,重試是安全做法
    if (loadedFrom == DISK && response.getContentLength() == 0) {
        Utils.closeQuietly(is);
        throw new ContentLengthException("Received response with 0 content-length header.");
    }
    if (loadedFrom == NETWORK && response.getContentLength() > 0) {
        stats.dispatchDownloadFinished(response.getContentLength());
    }
    return new Result(is, loadedFrom);
}

拿到結果後回到 run():

result = hunt();
if (result == null) {
    dispatcher.dispatchFailed(this);
} else {
    dispatcher.dispatchComplete(this);
}

接下來是 Dispatcher 的鏈路:dispatchComplete -> performComplete -> batch -> performBatchComplete -> 發消息給主線程。其中 performComplete 有一處值得留意——滿足策略時會把結果寫入緩存:

if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
    cache.set(hunter.getKey(), hunter.getResult());
}

主線程的處理:

case HUNTER_BATCH_COMPLETE: {
    List<BitmapHunter> batch = (List<BitmapHunter>) msg.obj;
    for (int i = 0, n = batch.size(); i < n; i++) {
        BitmapHunter hunter = batch.get(i);
        hunter.picasso.complete(hunter);
    }
    break;
}

後續調用鏈是 hunter.picasso.complete(hunter) -> deliverAction -> action.complete(result, from)。對 ImageView 而言就是 ImageViewAction 的 complete:

@Override
public void complete(Bitmap result, Picasso.LoadedFrom from) {
    if (result == null) {
        throw new AssertionError(
                String.format("Attempted to complete action with no result!\n%s", this));
    }
    ImageView target = this.target.get();
    if (target == null) {
        return;
    }
    Context context = picasso.context;
    boolean indicatorsEnabled = picasso.indicatorsEnabled;
    PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled);
    if (callback != null) {
        callback.onSuccess();
    }
}

最終由 PicassoDrawable.setBitmap() 把圖片設到 ImageView 上,這個類同時提供了淡入動畫。

最後以一張時序圖收尾:

文章同步至 GitHub:Picasso 源碼分析

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved