public static void loadResourceFromUrl(Context context, Uri uri, String cookie, String referer, BaseDataSubscriber dataSubscriber) { if (uri.getScheme().startsWith("http")) { JsonObject header = new JsonObject(); header.addProperty("Cookie", cookie); header.addProperty("Referer", referer); if (HProxy.isEnabled() && HProxy.isAllowPicture()) { HProxy proxy = new HProxy(uri.toString()); header.addProperty(proxy.getHeaderKey(), proxy.getHeaderValue()); } MyOkHttpNetworkFetcher.headers.put(uri, getGson().toJson(header)); } ImagePipeline imagePipeline = Fresco.getImagePipeline(); ImageRequestBuilder builder = ImageRequestBuilder.newBuilderWithSource(uri); ImageRequest request = builder.build(); DataSource<CloseableReference<PooledByteBuffer>> dataSource = imagePipeline.fetchEncodedImage(request, context); dataSource.subscribe(dataSubscriber, CallerThreadExecutor.getInstance()); }
@Override protected void onNewResultImpl(DataSource<CloseableReference<PooledByteBuffer>> dataSource) { if (!dataSource.isFinished() || dataSource.getResult() == null) { return; } // if we try to retrieve image file by cache key, it will return null // so we need to create a temp file, little bit hack :( PooledByteBufferInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new PooledByteBufferInputStream(dataSource.getResult().get()); outputStream = new FileOutputStream(mTempFile); IOUtils.copy(inputStream, outputStream); mFinished = true; onSuccess(mTempFile); } catch (IOException e) { onFail(e); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } }
@Override public void loadImage(Uri uri, final Callback callback) { ImageRequest request = ImageRequest.fromUri(uri); File localCache = getCacheFile(request); if (localCache.exists()) { callback.onCacheHit(localCache); } else { callback.onStart(); // ensure `onStart` is called before `onProgress` and `onFinish` callback.onProgress(0); // show 0 progress immediately ImagePipeline pipeline = Fresco.getImagePipeline(); DataSource<CloseableReference<PooledByteBuffer>> source = pipeline.fetchEncodedImage(request, true); source.subscribe(new ImageDownloadSubscriber(mAppContext) { @Override protected void onProgress(int progress) { callback.onProgress(progress); } @Override protected void onSuccess(File image) { callback.onFinish(); callback.onCacheMiss(image); } @Override protected void onFail(Throwable t) { // TODO: 12/11/2016 fail t.printStackTrace(); } }, mExecutorSupplier.forBackgroundTasks()); } }
@Override public void onProgressUpdate(DataSource<CloseableReference<PooledByteBuffer>> dataSource) { if (!mFinished) { onProgress((int) (dataSource.getProgress() * 100)); } }
@Override protected void onFailureImpl(DataSource<CloseableReference<PooledByteBuffer>> dataSource) { mFinished = true; onFail(new RuntimeException("onFailureImpl")); }