com.facebook.imagepipeline.core/ImagePipeline.java
[1]取图片从BitmapCache
>public DataSource<CloseableReference<CloseableImage>> fetchImageFromBitmapCache( ImageRequest imageRequest, Object callerContext)
>> submitFetchRequest()
>>>CloseableProducerToDataSourceAdapter.create()生产者到数据源的一个适配器
该适配器目录com.facebook.imagepipeline.datasource/CloseableProducerToDataSourceAdapter.java
@看看定义
CloseableProducerToDataSourceAdapter<T> extends AbstractProducerToDataSourceAdapter<CloseableReference<T>>
@跟踪create方法
create()---> super(producer, settableProducerContext, listener)父类的构造方法
>>producer.produceResults(createConsumer(), settableProducerContext)
执行父类构造方法,父类开始 告诉 生成者 开始生产作业了produceResults();
@那么这个producer生产者是谁呢?
:::::: producerSequence这玩意
> Producer<CloseableReference<CloseableImage>> producerSequence =
mProducerSequenceFactory.getDecodedImageProducerSequence(imageRequest);
^
@mProducerSequenceFactory工厂产生生产者
^
public Producer<CloseableReference<CloseableImage>> getDecodedImageProducerSequence(ImageRequest imageRequest) {
Producer<CloseableReference<CloseableImage>> pipelineSequence =
getBasicDecodedImageSequence(imageRequest);
if (imageRequest.getPostprocessor() != null) {
return getPostprocessorSequence(pipelineSequence);
} else {
return pipelineSequence;
}
}
@看看pipelineSequence怎么得来:
private Producer<CloseableReference<CloseableImage>> getBasicDecodedImageSequence(ImageRequest imageRequest) {
Preconditions.checkNotNull(imageRequest);//判空
Uri uri = imageRequest.getSourceUri();//图片地址
Preconditions.checkNotNull(uri, "Uri is null.");//判空
if (UriUtil.isNetworkUri(uri)) {//网络地址
return getNetworkFetchSequence();
} else if (UriUtil.isLocalFileUri(uri)) {//本地文件地址
if (MediaUtils.isVideo(MediaUtils.extractMime(uri.getPath()))) {
return getLocalVideoFileFetchSequence();
} else {
return getLocalImageFileFetchSequence();
}
} else if (UriUtil.isLocalContentUri(uri)) {//content地址 如 content://sms/inbox
return getLocalContentUriFetchSequence();
} else if (UriUtil.isLocalAssetUri(uri)) {//本地Asset地址
return getLocalAssetFetchSequence();
} else if (UriUtil.isLocalResourceUri(uri)) {//本地Resource地址
return getLocalResourceFetchSequence();
} else if (UriUtil.isDataUri(uri)) {
return getDataFetchSequence();
} else {
String uriString = uri.toString();
if (uriString.length() > 30) {
uriString = uriString.substring(0, 30) + "...";
}
throw new RuntimeException("Unsupported uri scheme! Uri is: " + uriString);
}
}
根据uri类型 来返回 不同的 Producer生产者.
@继续跟代码
1、如果是网络地址 getNetworkFetchSequence();
> mNetworkFetchSequence = newBitmapCacheGetToDecodeSequence(getCommonNetworkFetchToEncodedMemorySequence());
>>
private Producer<CloseableReference<CloseableImage>> newBitmapCacheGetToDecodeSequence(Producer<EncodedImage> inputProducer) {
DecodeProducer decodeProducer = mProducerFactory.newDecodeProducer(inputProducer);
return newBitmapCacheGetToBitmapCacheSequence(decodeProducer);
}
com.facebook.imagepipeline.core/ProducerFactory.java
先是 调用工厂类 ProducerFactory.newDecodeProducer得到一个DecodeProducer解码生产者
newBitmapCacheGetToBitmapCacheSequence(inputProducer)做了啥?
:ProducerFactory生了BitmapMemoryCacheProducer,进化成BitmapMemoryCacheKeyMultiplexProducer,再次进化ThreadHandoffProducer【这货后面有用到】
然并卵
return mProducerFactory.newBitmapMemoryCacheGetProducer(threadHandoffProducer);
> ||
public BitmapMemoryCacheGetProducer newBitmapMemoryCacheGetProducer(
Producer<CloseableReference<CloseableImage>> inputProducer) {
return new BitmapMemoryCacheGetProducer(mBitmapMemoryCache, mCacheKeyFactory, inputProducer);
}
最后超级进化成 @BitmapMemoryCacheGetProducer
@2大工厂 @ProducerSequenceFactory 和 @ProducerFactory 前面又字面意思可以理解 一系列工厂,肯定是总厂,下面很多分厂;
回到主线 producer.produceResults(createConsumer(), settableProducerContext); 找到了 生产者就要开始生产了!!!
主角是 BitmapMemoryCacheGetProducer 官方注释是 只读的生产者,暂时有点懵逼
主角父亲是BitmapMemoryCacheProducer这货
@Override
public void produceResults(final Consumer<CloseableReference<CloseableImage>> consumer, final ProducerContext producerContext) {
final ProducerListener listener = producerContext.getListener();
final String requestId = producerContext.getId();
listener.onProducerStart(requestId, getProducerName());//告诉listener开始生产
final ImageRequest imageRequest = producerContext.getImageRequest();
final CacheKey cacheKey = mCacheKeyFactory.getBitmapCacheKey(imageRequest);//先取缓存钥匙
CloseableReference<CloseableImage> cachedReference = mMemoryCache.get(cacheKey);//取图片
if (cachedReference != null) {//缓存存在
boolean isFinal = cachedReference.get().getQualityInfo().isOfFullQuality();
if (isFinal) {
listener.onProducerFinishWithSuccess(
requestId,
getProducerName(),
listener.requiresExtraMap(requestId) ? ImmutableMap.of(VALUE_FOUND, "true") : null);
consumer.onProgressUpdate(1f);//进度报告 完美
}
consumer.onNewResult(cachedReference, isFinal);//消费者 得到 产品
cachedReference.close();
if (isFinal) {
return;
}
}
if (producerContext.getLowestPermittedRequestLevel().getValue() >=
ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE.getValue()) {//最低请求等级判断 ,BITMAP_MEMORY_CACHE是最高等级
listener.onProducerFinishWithSuccess(
requestId,
getProducerName(),
listener.requiresExtraMap(requestId) ? ImmutableMap.of(VALUE_FOUND, "false") : null);
consumer.onNewResult(null, true);
return;
}
//包装消费者
Consumer<CloseableReference<CloseableImage>> wrappedConsumer = wrapConsumer(consumer, cacheKey);
listener.onProducerFinishWithSuccess(requestId,
getProducerName(),
listener.requiresExtraMap(requestId) ? ImmutableMap.of(VALUE_FOUND, "false") : null);
mInputProducer.produceResults(wrappedConsumer, producerContext);//再次生产
}
@RequestLevel.java 是com.facebook.imagepipeline.request.ImageRequest的内部类
/* Fetch (from the network or local storage) */
FULL_FETCH(1),
/* Disk caching */
DISK_CACHE(2),
/* Encoded memory caching */
ENCODED_MEMORY_CACHE(3),
/* Bitmap caching */
BITMAP_MEMORY_CACHE(4);
mInputProducer是谁呢? 另一个生产者闪亮登场了 ThreadHandoffProducer 这货
这货是 怎么 产生的?
ThreadHandoffProducer<CloseableReference<CloseableImage>> threadHandoffProducer =
mProducerFactory.newBackgroundThreadHandoffProducer(bitmapKeyMultiplexProducer, mThreadHandoffProducerQueue);
还是离不开ProducerFactory工厂类
参数2:mThreadHandoffProducerQueue ,它里面 有一个Executor 线程执行器 和 ArrayList<Runnable>容器;
其实 就是 一个 线程池吧。
//ThreadHandoffProducer开始生产
@Override
public void produceResults(final Consumer<T> consumer, final ProducerContext context) {
final ProducerListener producerListener = context.getListener();
final String requestId = context.getId();
final StatefulProducerRunnable<T> statefulRunnable = new StatefulProducerRunnable<T>(
consumer, producerListener, PRODUCER_NAME, requestId) {
@Override
protected void onSuccess(T ignored) {
producerListener.onProducerFinishWithSuccess(requestId, PRODUCER_NAME, null);
mInputProducer.produceResults(consumer, context);//关键是 这句代码
}
@Override
protected void disposeResult(T ignored) {
}
@Override
protected T getResult() throws Exception {
return null;
}
};
context.addCallbacks(new BaseProducerContextCallbacks() {
@Override
public void onCancellationRequested() {
statefulRunnable.cancel();
mThreadHandoffProducerQueue.remove(statefulRunnable);
}
});
mThreadHandoffProducerQueue.addToQueueOrExecute(statefulRunnable); //丢到线程池 执行
}
在 onSuccess()回调方法里 ThreadHandoffProducer的mInputProducer开始 登场,
此mInputProducer引用的对象是 BitmapMemoryCacheKeyMultiplexProducer bitmapKeyMultiplexProducer =
mProducerFactory.newBitmapMemoryCacheKeyMultiplexProducer(bitmapMemoryCacheProducer);
顺藤摸瓜 跟到BitmapMemoryCacheKeyMultiplexProducer的父类 MultiplexProducer
>produceResults()
>>startInputProducerIfHasAttachedConsumers()
>>>mInputProducer.produceResults(forwardingConsumer, multiplexProducerContext);
最后 又把任务交给 另一个生产者mInputProducer
BitmapMemoryCacheProducer bitmapMemoryCacheProducer =
mProducerFactory.newBitmapMemoryCacheProducer(inputProducer);
看看 BitmapMemoryCacheProducer 的
@Override
public void produceResults(final Consumer<CloseableReference<CloseableImage>> consumer,
final ProducerContext producerContext) {
......
Consumer<CloseableReference<CloseableImage>> wrappedConsumer = wrapConsumer(consumer, cacheKey);
listener.onProducerFinishWithSuccess(
requestId,
getProducerName(),
listener.requiresExtraMap(requestId) ? ImmutableMap.of(VALUE_FOUND, "false") : null);
mInputProducer.produceResults(wrappedConsumer, producerContext);
}
哭笑不得 又交给 另一个生产者mInputProducer
只能往回看代码了 :
DecodeProducer decodeProducer = mProducerFactory.newDecodeProducer(inputProducer);
解码生产者
@Override
public void produceResults(final Consumer<CloseableReference<CloseableImage>> consumer,
final ProducerContext producerContext) {
final ImageRequest imageRequest = producerContext.getImageRequest();
ProgressiveDecoder progressiveDecoder;
if (!UriUtil.isNetworkUri(imageRequest.getSourceUri())) {//不是网络地址
progressiveDecoder = new LocalImagesProgressiveDecoder(consumer, producerContext);
} else { //是网络图片地址
ProgressiveJpegParser jpegParser = new ProgressiveJpegParser(mByteArrayPool);
progressiveDecoder = new NetworkImagesProgressiveDecoder(consumer,
producerContext,
jpegParser,
mProgressiveJpegConfig);
}
mInputProducer.produceResults(progressiveDecoder, producerContext);
}
继续跟 这个 mInputProducer,找源头吧
private synchronized Producer<CloseableReference<CloseableImage>> getNetworkFetchSequence() {
if (mNetworkFetchSequence == null) {
mNetworkFetchSequence = newBitmapCacheGetToDecodeSequence(getCommonNetworkFetchToEncodedMemorySequence());
}
return mNetworkFetchSequence;
}
到这里 getCommonNetworkFetchToEncodedMemorySequence()返回生产者
/**
* multiplex -> encoded cache -> disk cache -> (webp transcode) -> network fetch.
*/
private synchronized Producer<EncodedImage> getCommonNetworkFetchToEncodedMemorySequence() {
if (mCommonNetworkFetchToEncodedMemorySequence == null) {
Producer<EncodedImage> inputProducer = newEncodedCacheMultiplexToTranscodeSequence(
mProducerFactory.newNetworkFetchProducer(mNetworkFetcher)); //这里是生存者 源头
mCommonNetworkFetchToEncodedMemorySequence =
ProducerFactory.newAddImageTransformMetaDataProducer(inputProducer);
if (mResizeAndRotateEnabledForNetwork && !mDownsampleEnabled) { //需要调整大小 和 旋转
mCommonNetworkFetchToEncodedMemorySequence = mProducerFactory.newResizeAndRotateProducer(
mCommonNetworkFetchToEncodedMemorySequence);
}
}
return mCommonNetworkFetchToEncodedMemorySequence;
}
直接看源头NetworkFetchProducer 网络获取生产者(从网络获取图片呗)
@Override
public void produceResults(Consumer<EncodedImage> consumer, ProducerContext context) {
context.getListener()
.onProducerStart(context.getId(), PRODUCER_NAME);
final FetchState fetchState = mNetworkFetcher.createFetchState(consumer, context);
mNetworkFetcher.fetch(fetchState, new NetworkFetcher.Callback() {
@Override
public void onResponse(InputStream response, int responseLength) throws IOException {
NetworkFetchProducer.this.onResponse(fetchState, response, responseLength);
}
@Override
public void onFailure(Throwable throwable) {
NetworkFetchProducer.this.onFailure(fetchState, throwable);
}
@Override
public void onCancellation() {
NetworkFetchProducer.this.onCancellation(fetchState);
}
});
}
mNetworkFetcher是 由 ImagePipelineConfig 初始化的 时候配置的
mNetworkFetcher = builder.mNetworkFetcher == null ?
new HttpUrlConnectionNetworkFetcher() : builder.mNetworkFetcher;
默认配置下ImagePipelineConfig.Builder类的 mNetworkFetcher为 null;
mNetworkFetcher 指向的 就是 HttpUrlConnectionNetworkFetcher,Fresco默认的网络连接用的是HttpUrlConnection;
HttpUrlConnectionNetworkFetcher的 fetch() 方法里
@Override
public void fetch(final FetchState fetchState, final Callback callback) {
final Future<?> future = mExecutorService.submit(new Runnable() {
@Override
public void run() {
fetchSync(fetchState, callback);
}
});//开了个线程执行下载图片操作
......
}
void fetchSync(FetchState fetchState, Callback callback) {
HttpURLConnection connection = null;
try {
connection = downloadFrom(fetchState.getUri(), MAX_REDIRECTS);//终于要下载了
if (connection != null) {
callback.onResponse(connection.getInputStream(), -1);
}
} catch (IOException e) {
callback.onFailure(e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
以上是网络加载图片步骤...