Picasso源码解析
来源:互联网 发布:网络成瘾症心理干预 编辑:程序博客网 时间:2024/05/21 13:27
我一般看源码都是从它的使用入手,从它的使用来遍历它的执行过程.Picasso的使用只需一行代码,所以从这行代码开始.
这行代码就不用我写了吧.反正肯定要进入load方法.进入load方法一看,还要进入RequestCreator 类.
RequestCreator类如下:
从这个变量Request.Builder data和它的一系列方法可以看出,这个类是对图片设置一些个人的请求,而这些请求被包装成一个Request类.这个类与一些其他的设置将一并传入一个类(这个类是啥了?).配置好之后一定会进入into方法.
方法流程如下:
1.createRequest,创建请求
2.createKey,创建请求键值
3.看缓存中是否有图片,有的话setBitmap
4.没有的话,就将request和一些其他的配置传入action类.
5.submit,对action这个任务进行执行.
此时我们进入Picasso类中看submit这个方法,发现最终要使用Dispatcher这个类.
private final Request.Builder data;private boolean noFade;private boolean deferred;private boolean setPlaceholder = true;private int placeholderResId;private int errorResId;private int memoryPolicy;private int networkPolicy;private Drawable placeholderDrawable;private Drawable errorDrawable;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."); } int width = target.getWidth(); int height = target.getHeight(); if (width == 0 || height == 0 || target.isLayoutRequested()) { 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); }
Dispatcher类如下:
此类是一个调度器,对任务进行调度与分发.我们将action传入dispatchSubmit方法里,它将会将这个任务通过handler分发到handlerThread线程中执行,也就是执行performSubmit这个方法.下面是这个方法的执行流程:
1.hunterMap.get(action.getKey()),此操作从map中取出之前之前的BitmapHunter,如果没有,说明此任务是一个新的任务
2.forRequest(action.getPicasso(), this, cache, stats, action),创建请求
3.service.submit(hunter),调用executor执行线程.
4.hunterMap.put(action.getKey(), hunter),把已经执行的任务放入map中,避免重复操作.
在执行完submit后如果成功了,就要进入到performComplete中了,此方法中又将进入到batch方法中,batch是一个存储hunter的集合,它将hunter加入其中,而不是立即就将得到后的图片显示出来.再看它后面的这步操作handler.sendEmptyMessageDelayed(HUNTER_DELAY_NEXT_BATCH, BATCH_DELAY);寻着它我们要进入到performBatchComplete方法,可以看到它将hunter集合通过mainHandler传到主线程中了.mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));此时我们回到Picasso类中找到这个mainHandler,可以看到这个变量:static final Handler HANDLER.在这个变量中有这个操作,hunter.picasso.complete(hunter);再次进入到Picasso中的complete方法,再进入到此方法的deliverAction方法中,你会方向这步操作action.complete(result, from);此时你到action的具体实现类找这个方法,它有一步操作PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled);终于现身了,真是众里寻她千百度啊.
这其中涉及到几个重要的类BitmapHunter,Action,等.下面会进行详细的分析.
void dispatchSubmit(Action action) { handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));}void performSubmit(Action action, boolean dismissFailed) { 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; } 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; } hunter = forRequest(action.getPicasso(), this, cache, stats, action); hunter.future = service.submit(hunter); hunterMap.put(action.getKey(), hunter); if (dismissFailed) { failedActions.remove(action.getTarget()); } if (action.getPicasso().loggingEnabled) { log(OWNER_DISPATCHER, VERB_ENQUEUED, action.request.logId()); } }void performComplete(BitmapHunter hunter) { if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) { cache.set(hunter.getKey(), hunter.getResult()); } hunterMap.remove(hunter.getKey()); batch(hunter); if (hunter.getPicasso().loggingEnabled) { log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for completion"); }private void batch(BitmapHunter hunter) { if (hunter.isCancelled()) { return; } batch.add(hunter); if (!handler.hasMessages(HUNTER_DELAY_NEXT_BATCH)) { handler.sendEmptyMessageDelayed(HUNTER_DELAY_NEXT_BATCH, BATCH_DELAY); } }void performBatchComplete() { List<BitmapHunter> copy = new ArrayList<>(batch); batch.clear(); mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy)); logBatch(copy); }private static class DispatcherHandler extends Handler { private final Dispatcher dispatcher; public DispatcherHandler(Looper looper, Dispatcher dispatcher) { super(looper); this.dispatcher = dispatcher; } @Override public void handleMessage(final Message msg) { switch (msg.what) { case REQUEST_SUBMIT: { Action action = (Action) msg.obj; dispatcher.performSubmit(action); break; } case REQUEST_CANCEL: { Action action = (Action) msg.obj; dispatcher.performCancel(action); break; } case TAG_PAUSE: { Object tag = msg.obj; dispatcher.performPauseTag(tag); break; } case TAG_RESUME: { Object tag = msg.obj; dispatcher.performResumeTag(tag); break; } case HUNTER_COMPLETE: { BitmapHunter hunter = (BitmapHunter) msg.obj; dispatcher.performComplete(hunter); break; } case HUNTER_RETRY: { BitmapHunter hunter = (BitmapHunter) msg.obj; dispatcher.performRetry(hunter); break; } case HUNTER_DECODE_FAILED: { BitmapHunter hunter = (BitmapHunter) msg.obj; dispatcher.performError(hunter, false); break; } case HUNTER_DELAY_NEXT_BATCH: { dispatcher.performBatchComplete(); break; } case NETWORK_STATE_CHANGE: { NetworkInfo info = (NetworkInfo) msg.obj; dispatcher.performNetworkStateChange(info); break; } case AIRPLANE_MODE_CHANGE: { dispatcher.performAirplaneModeChange(msg.arg1 == AIRPLANE_MODE_ON); break; } default: Picasso.HANDLER.post(new Runnable() { @Override public void run() { throw new AssertionError("Unknown handler message received: " + msg.what); } }); } } }
BitmapHunter类如下:
run()方法执行过程:
1.hunt(), 加载图片
2.加载为空,dispatchFailed,发送失败事件
3.得到图片,dispatchComplete,在上面的dispatcher类中分析过.
hunt()方法执行过程:
1.shouldReadFromMemoryCache(memoryPolicy),判断是否在缓存中.
2.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
RequestHandler.Result result = requestHandler.load(data, networkPolicy);
不在缓存中,就到网上找呗.这里的RequestHandler类对不同uri进行解析,最后返回result.
@Override public void run() { try { updateThreadName(data); if (picasso.loggingEnabled) { log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this)); } result = hunt(); if (result == null) { dispatcher.dispatchFailed(this); } else { dispatcher.dispatchComplete(this); } } catch (NetworkRequestHandler.ResponseException e) { if (!NetworkPolicy.isOfflineOnly(e.networkPolicy) || e.code != 504) { exception = e; } dispatcher.dispatchFailed(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); } } Bitmap hunt() throws IOException { Bitmap bitmap = null; if (shouldReadFromMemoryCache(memoryPolicy)) { bitmap = cache.get(key); if (bitmap != null) { stats.dispatchCacheHit(); loadedFrom = MEMORY; if (picasso.loggingEnabled) { log(OWNER_HUNTER, VERB_DECODED, data.logId(), "from cache"); } return bitmap; } } networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy; RequestHandler.Result result = requestHandler.load(data, networkPolicy); if (result != null) { loadedFrom = result.getLoadedFrom(); exifOrientation = result.getExifOrientation(); bitmap = result.getBitmap(); // If there was no Bitmap then we need to decode it from the stream. if (bitmap == null) { Source source = result.getSource(); try { bitmap = decodeStream(source, data); } finally { try { //noinspection ConstantConditions If bitmap is null then source is guranteed non-null. source.close(); } catch (IOException ignored) { } } } } //........................ //........................ return bitmap; }
Action类:
此类是一个接口,它定义了你获取一个图片应该要传的值,包括request,imageview,和一些其他的配置.它就像是一个你将要操作的行为一样,携带了你该要带的东西,只为最后获取到图片.这里边对target进行弱引用,便于gc回收.它的一个强大的地方就是使用泛型,你可以指定不同的view来显示图片.里边的俩个虚拟方法,留给特定的子类实现,任你对图片为所欲为.
abstract void complete(Bitmap result, Picasso.LoadedFrom from);
abstract void error(Exception e);
RequestHandler类:
此类是一个接口,定义了不同类型uri的加载方式,通过继承它来实现不同的加载.
NetWorkRequestHandler:
继承RequestHandler类的子类,对网络图片进行加载,Picasso内部的网络加载用的是OKhttp.它的ImageDownload的默认实现就是OKhttp3download.
- Picasso源码解析
- Picasso源码解析 一
- Picasso源码解析
- Picasso源码解析
- Picasso源码解析
- Picasso源码解析
- picasso源码解析3
- picasso 源码解析
- Picasso源码解析
- Picasso源码解析
- Picasso源码解析
- picasso源码简单解析
- Picasso 用法及源码解析
- picasso图片框架源码解析
- Picasso源码完全解析(二)--Picasso实例的创建
- Picasso框架源码解析(一)。
- Picasso的使用和源码解析
- Picasso源码的简单解析(一)
- 一位Android开发者吐血分享面试的点点滴滴
- eclipse编写第一个osgi bundle的小demo,同时导出osgi化的bundle
- 编程第八十三天
- 兰州烧饼
- java关键字
- Picasso源码解析
- 一个程序员的修炼
- CocoaPods使用详解
- 编程第八十四天
- 理解Spring MVC中的异步处理请求(下)
- 常用的头文件和函数
- display:box和flex的区别
- 将QWebkit 转化到 Qt 5.8下使用QWebEngine
- linux 常用命令