RequestHandler是Picasso获取图片逻辑的实现类。
RequestHandler.Result
Result类是图片请求Request的处理结果。
public static final class Result { private final Picasso.LoadedFrom loadedFrom;//图片的来源:内存、磁盘、网络 private final Bitmap bitmap;//图片数据,和InputStream只能二者选一 private final InputStream stream;//图片数据,和Bitmap只能二者选一 ...}复制代码
自定义RequestHandler
Picasso框架提供了7个RequestHandler和一个BitmapHunter.ERRORING_HANDLER,已经能够很好地满足我们的需求。同时,Picasso也允许我们根据实际需求自定义RequestHandler。 自定义RequestHandler只需要继承RequestHandler并实现两个抽象方法,然后通过Picasso.Builder的addRequestHandler方法添加到Picasso中。
public abstract class RequestHandler { ... public abstract boolean canHandleRequest(Request data);//判断是否能够处理图片请求 @Nullable public abstract Result load(Request request, int networkPolicy) throws IOException;//根据图片请求和网络策略获取图片,并返回处理结果Result ...}复制代码
RequestHandler还提供了静态方法createBitmapOptions、requiresInSampleSize、calculateInSampleSize方便对图片进行压缩。
RequestHandler责任链
Picasso把默认和自定义的RequestHandler添加到属性requestHandlers中。添加顺序如下:
//extraRequestHandlers是自定义RequestHandler列表。int extraCount = (extraRequestHandlers != null ? extraRequestHandlers.size() : 0);ListallRequestHandlers = new ArrayList (builtInHandlers + extraCount);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);复制代码
这些RequestHandler是以责任链模式被调用的,请看BitmapHunter的forRequest方法。
static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action) { Request request = action.getRequest(); ListrequestHandlers = picasso.getRequestHandlers(); for (int i = 0, count = requestHandlers.size(); i < count; i++) { RequestHandler requestHandler = requestHandlers.get(i); if (requestHandler.canHandleRequest(request)) { //从前向后迭代直到找到能处理该Request的RequestHandler。 return new BitmapHunter(picasso, dispatcher, cache, stats, action, requestHandler); } } //如果没能找到合适的RequestHandler,则交给ERRORING_HANDLER,该Handler的处理方式是直接抛出异常。 return new BitmapHunter(picasso, dispatcher, cache, stats, action, ERRORING_HANDLER);}复制代码
NetworkRequestHandler
NetworkRequestHandler处理网络图片请求,图片下载逻辑是由Downloader实现的。
class NetworkRequestHandler extends RequestHandler { static final int RETRY_COUNT = 2; //处理http或者https请求 @Override public boolean canHandleRequest(Request data) { String scheme = data.uri.getScheme(); return (SCHEME_HTTP.equals(scheme) || SCHEME_HTTPS.equals(scheme)); } //下载失败会重试2次 @Override int getRetryCount() { return RETRY_COUNT; } //支持失败重试 @Override boolean supportsReplay() { return true; }}复制代码