picasso的使用
//加載一張圖片
Picasso.with(this).load("url").placeholder(R.mipmap.ic_default).into(imageView);
//加載一張圖片並設置一個回調接口
Picasso.with(this).load("url").placeholder(R.mipmap.ic_default).into(imageView, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
}
});
//預加載一張圖片
Picasso.with(this).load("url").fetch();
//同步加載一張圖片,注意只能在子線程中調用並且Bitmap不會被緩存到內存裏.
new Thread() {
@Override
public void run() {
try {
final Bitmap bitmap = Picasso.with(getApplicationContext()).load("url").get();
mHandler.post(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
//加載一張圖片並自適應imageView的大小,如果imageView設置了wrap_content,會顯示不出來.直到該ImageView的
//LayoutParams被設置而且調用了該View的ViewTreeObserver.OnPreDrawListener回調接口後纔會顯示.
Picasso.with(this).load("url").priority(Picasso.Priority.HIGH).fit().into(imageView);
//加載一張圖片並按照指定尺寸以centerCrop()的形式縮放.
Picasso.with(this).load("url").resize(200,200).centerCrop().into(imageView);
//加載一張圖片並按照指定尺寸以centerInside()的形式縮放.並設置加載的優先級爲高.注意centerInside()或centerCrop()
//只能同時使用一種,而且必須指定resize()或者resizeDimen();
Picasso.with(this).load("url").resize(400,400).centerInside().priority(Picasso.Priority.HIGH).into(imageView);
//加載一張圖片旋轉並且添加一個Transformation,可以對圖片進行各種變化處理,例如圓形頭像.
Picasso.with(this).load("url").rotate(10).transform(new Transformation() {
@Override
public Bitmap transform(Bitmap source) {
//處理Bitmap
return null;
}
@Override
public String key() {
return null;
}
}).into(imageView);
//加載一張圖片並設置tag,可以通過tag來暫定或者繼續加載,可以用於當ListView滾動是暫定加載.停止滾動恢復加載.
Picasso.with(this).load("url").tag(mContext).into(imageView);
Picasso.with(this).pauseTag(mContext);
Picasso.with(this).resumeTag(mContxt);
一張圖片加載的過程
創建->入隊->執行->解碼->變換->批處理->完成->分發->顯示(可選)
源碼分析
從最簡單的加載一張圖片開始看起 Picasso.with(this).load(url).into(imageView);讓我們來看看Picasso.with(context)做了什麼,
static volatile Picasso singleton = null;
public static Picasso with(Context context) {
if (singleton == null) {
synchronized (Picasso.class) {
if (singleton == null) {
singleton = new Builder(context).build();
}
}
}
return singleton;
}
顯然是由new Builder(context).build()創建的單例。builder是picasso的靜態內部類,其中的build()方法定義:
/** Create the {@link Picasso} instance. */
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);
}
讓我們來看看picasso的構造函數裏做了些什麼
Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled) {
this.context = context;
this.dispatcher = dispatcher;
this.cache = cache;
this.listener = listener;
this.requestTransformer = requestTransformer;
this.defaultBitmapConfig = defaultBitmapConfig;
int builtInHandlers = 7; // Adjust this as internal handlers are added or removed.
int extraCount = (extraRequestHandlers != null ? extraRequestHandlers.size() : 0);
List<RequestHandler> allRequestHandlers =
new ArrayList<RequestHandler>(builtInHandlers + extraCount);
// ResourceRequestHandler needs to be the first in the list to avoid
// forcing other RequestHandlers to perform null checks on request.uri
// to cover the (request.resourceId != 0) case.
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);
this.stats = stats;
this.targetToAction = new WeakHashMap<Object, Action>();
this.targetToDeferredRequestCreator = new WeakHashMap<ImageView, DeferredRequestCreator>();
this.indicatorsEnabled = indicatorsEnabled;
this.loggingEnabled = loggingEnabled;
this.referenceQueue = new ReferenceQueue<Object>();
this.cleanupThread = new CleanupThread(referenceQueue, HANDLER);
this.cleanupThread.start();
}
基本上就是給內部變量賦值,作用如下:
使用默認的緩存策略,內存緩存基於LruCache,磁盤緩存基於http緩存,HttpResponseCache
創建默認的下載器
創建默認的線程池(3個worker線程)
創建默認的Transformer,這個Transformer什麼事情也不幹,只負責轉發請求
創建默認的監控器(Stats),用於統計緩存命中率、下載時長等等
創建默認的處理器集合,即RequestHandlers.它們分別會處理不同的加載請求
接着初始化RequestHandler的一個ArrayList,那麼RequestHandler究竟是幹啥的呢,官方源碼上的註釋說的很清楚了,我暫時還沒用過,就不做過多瞭解。
/**
* {@code RequestHandler} allows you to extend Picasso to load images in ways that are not
* supported by default in the library.
* <p>
* <h2>Usage</h2>
* {@code RequestHandler} must be subclassed to be used. You will have to override two methods
* ({@link #canHandleRequest(Request)} and {@link #load(Request, int)}) with your custom logic to
* load images.
* <p>
* You should then register your {@link RequestHandler} using
* {@link Picasso.Builder#addRequestHandler(RequestHandler)}
* <p>
* <b>Note:</b> This is a beta feature. The API is subject to change in a backwards incompatible
* way at any time.
*
* @see Picasso.Builder#addRequestHandler(RequestHandler)
*/
接着往下看load方法。
public RequestCreator load(Uri uri) {
return new RequestCreator(this, uri, 0);
}
返回了一個新建的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);
}
首先是持有一個Picasso的對象,然後構建一個Request的Builder對象,將我們需要加載的圖片的信息都保存在data裏,在我們通過.centerCrop()或者.transform()等等方法的時候實際上也就是改變data內的對應的變量標識,再到處理的階段根據這些參數來進行對應的操作,所以在我們調用into()方法之前,所有的操作都是在設定我們需要處理的參數,真正的操作都是有into()方法引起的。
/**
* Asynchronously fulfills the request into the specified {@link ImageView}.
* <p>
* <em>Note:</em> This method keeps a weak reference to the {@link ImageView} instance and will
* automatically support object recycling.
*/
public void into(ImageView target) {
into(target, null);
}
/**
* Asynchronously fulfills the request into the specified {@link ImageView} and invokes the
* target {@link Callback} if it's not {@code null}.
* <p>
* <em>Note:</em> The {@link Callback} param is a strong reference and will prevent your
* {@link android.app.Activity} or {@link android.app.Fragment} from being garbage collected. If
* you use this method, it is <b>strongly</b> recommended you invoke an adjacent
* {@link Picasso#cancelRequest(android.widget.ImageView)} call to prevent temporary leaking.
*/
public void into(ImageView target, Callback callback) {
long started = System.nanoTime();
//check that method call happens from the main thread
checkMain();
if (target == null) {
throw new IllegalArgumentException("Target must not be null.");
}
//如果沒有設置需要加載的uri,或者resourceId
if (!data.hasImage()) {
picasso.cancelRequest(target);
//如果設置佔位圖片,直接加載並返回
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
return;
}
//如果是延時加載,也就是選擇了fit()模式
if (deferred) {
//fit()模式是適應target的寬高加載,所以並不能手動設置resize,如果設置就拋出異常
if (data.hasSize()) {
throw new IllegalStateException("Fit cannot be used with resize.");
}
int width = target.getWidth();
int height = target.getHeight();
if (width == 0 || height == 0 || target.isLayoutRequested()) {
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
//監聽ImageView的ViewTreeObserver.OnPreDrawListener接口,一旦ImageView
//的寬高被賦值,就按照ImageView的寬高繼續加載.
picasso.defer(target, new DeferredRequestCreator(this, target, callback));
return;
}
data.resize(width, height);
}
Request request = createRequest(started);
String requestKey = createKey(request);
if (shouldReadFromMemoryCache(memoryPolicy)) {
//通過LruCache來讀取內存裏的緩存圖片
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對象,由於我們是往ImageView里加載圖片,所以這裏創建的是一個ImageViewAction對象
Action action =
new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
errorDrawable, requestKey, tag, callback, noFade);
//將Action對象入列提交
picasso.enqueueAndSubmit(action);
}
整個流程看下來應該是比較清晰的,最後是創建了一個ImageViewAction對象並通過picasso提交,這裏簡要說明一下ImageViewAction,實際上Picasso會根據我們調用的不同方式來實例化不同的Action對象,當我們需要往ImageView里加載圖片的時候會創建ImageViewAction對象,如果是往實現了Target接口的對象里加載圖片是則會創建TargetAction對象,這些Action類的實現類不僅保存了這次加載需要的所有信息,還提供了加載完成後的回調方法.也是由子類實現並用來完成不同的調用的。然後讓我們繼續去看
picasso.enqueueAndSubmit(action)方法:
void enqueueAndSubmit(Action action) {
Object target = action.getTarget();
//取消這個target已經有的action.
if (target != null && targetToAction.get(target) != action) {
// This will also check we are on the main thread.
cancelExistingRequest(target);
targetToAction.put(target, action);
}
submit(action);
}
//調用dispatcher來派發action
void submit(Action action) {
dispatcher.dispatchSubmit(action);
}
void dispatchSubmit(Action action) {
handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
}
看到通過一個handler對象發送了一個REQUEST_SUBMIT的消息,那麼這個handler是存在與哪個線程的呢?
Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
Downloader downloader, Cache cache, Stats stats) {
this.dispatcherThread = new DispatcherThread();
this.dispatcherThread.start();
this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);
this.mainThreadHandler = mainThreadHandler;
}
static class DispatcherThread extends HandlerThread {
DispatcherThread() {
super(Utils.THREAD_PREFIX + DISPATCHER_THREAD_NAME, THREAD_PRIORITY_BACKGROUND);
}
}
上面是Dispatcher的構造方法(省略了部分代碼),可以看到先是創建了一個HandlerThread對象,然後創建了一個DispatcherHandler對象,這個handler就是剛剛用來發送REQUEST_SUBMIT消息的handler,這裏我們就明白了原來是通過Dispatcher類裏的一個子線程裏的handler不斷的派發我們的消息,這裏是用來派發我們的REQUEST_SUBMIT消息,而且最終是調用了 dispatcher.performSubmit(action);方法:
void performSubmit(Action action) {
performSubmit(action, true);
}
void performSubmit(Action action, boolean dismissFailed) {
//是否該tag的請求被暫停
if (pausedTags.contains(action.getTag())) {
pausedActions.put(action.getTarget(), action);
if (action.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_PAUSED, action.request.logId(),
"because tag '" + action.getTag() + "' is paused");
}
return;
}
//通過action的key來在hunterMap查找是否有相同的hunter,這個key裏保存的是我們
//的uri或者resourceId和一些參數,如果都是一樣就將這些action合併到一個
//BitmapHunter裏去.
BitmapHunter hunter = hunterMap.get(action.getKey());
if (hunter != null) {
hunter.attach(action);
return;
}
if (service.isShutdown()) {
if (action.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_IGNORED, action.request.logId(), "because shut down");
}
return;
}
//創建BitmapHunter對象
hunter = forRequest(action.getPicasso(), this, cache, stats, action);
//通過service執行hunter並返回一個future對象
hunter.future = service.submit(hunter);
//將hunter添加到hunterMap中
hunterMap.put(action.getKey(), hunter);
if (dismissFailed) {
failedActions.remove(action.getTarget());
}
if (action.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_ENQUEUED, action.request.logId());
}
}