最近一个项目中需要实现图片加载时下载进度百分比的展示。如果使用原始的HttpUrlConnection方式来加载图片的话,实现起来就非常简单了,直接读取InputStream时将进度回调到上层即可。在Glide中有这样的实现方式么?网上查到的都是使用okhttp方式来加载的示例,其实用系统的HttpUrlConnection方式来加载也是能够实现的。
因为Glide并没有直接暴露出下载进度这个信息,需要研究下有没有办法重写掉Glide的图片下载这个流程。很自然的想起Glide有个接口能够重写掉加载的一些过程:
<code>com.bumptech.glide.RequestManager#using(com.bumptech.glide.load.model.stream.StreamModelLoader)</code>
看一下文档中这个方法的定义:
- Returns a request builder that uses the given {@link com.bumptech.glide.load.model.stream.StreamModelLoader} to* fetch an {@link InputStream} for loading images.
可以通过这个方法重写Glide获取图片的InputStream,完全代理掉网络模块。网上比较多的例子是通过okhttp方式来重写网络模块,但实际用什么网络模块是没有任何关系的。如何实现StreamModelLoader实际上在Glide源码中也有非常多的例子。因为我实现的是单次请求时的网络模块替换,StreamModelLoader中的cache逻辑完全可以不用去理会,关注核心点的接口就行了,简单的实现如下:
<pre>
public class ImageUrlLoader implements StreamModelLoader<GlideUrl> {
private InputStreamReadCallback inputStreamReadCallback;
public ImageUrlLoader(InputStreamReadCallback inputStreamReadCallback) {
this.inputStreamReadCallback = inputStreamReadCallback;
}
@Override
public DataFetcher<InputStream> getResourceFetcher(GlideUrl model, int width, int height) {
//这里简单粗暴,直接返回用于获得网络InputStream的DataFetcher。内部才是真正读网络的逻辑,所以将读网络的回调传进去
return new HttpUrlFetcher(model, inputStreamReadCallback);
}
}
</pre>
HttpUrlFetcher在Glide中有默认实现,我这里的实现跟它提供的没有太多区别,唯一的区别就是将回调传到InputStream中的Wrapper里面去,让读取网络进度时能够将进度回调出来。
<pre>
/**
- A DataFetcher that retrieves an {@link java.io.InputStream} for a Url.
*/
public class HttpUrlFetcher implements DataFetcher<InputStream> {
private static final String TAG = "HttpUrlFetcher";
private static final int MAXIMUM_REDIRECTS = 5;
private final GlideUrl glideUrl;
private HttpURLConnection urlConnection;
private InputStream stream;
private volatile boolean isCancelled;
private InputStreamReadCallback inputStreamReadCallback;
// Visible for testing.
HttpUrlFetcher(GlideUrl glideUrl, InputStreamReadCallback inputStreamReadCallback) {
this.glideUrl = glideUrl;
this.inputStreamReadCallback = inputStreamReadCallback;
}
@Override
public InputStream loadData(Priority priority) throws Exception {
return loadDataWithRedirects(glideUrl.toURL(), 0 /*redirects*/, null /*lastUrl*/, glideUrl.getHeaders());
}
private InputStream loadDataWithRedirects(URL url, int redirects, URL lastUrl, Map<String, String> headers)
throws IOException {
if (redirects >= MAXIMUM_REDIRECTS) {
throw new IOException("Too many (> " + MAXIMUM_REDIRECTS + ") redirects!");
} else {
// Comparing the URLs using .equals performs additional network I/O and is generally broken.
// See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html.
try {
if (lastUrl != null && url.toURI().equals(lastUrl.toURI())) {
throw new IOException("In re-direct loop");
}
} catch (URISyntaxException e) {
// Do nothing, this is best effort.
}
}
urlConnection = (HttpURLConnection) url.openConnection();
for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
urlConnection.addRequestProperty(headerEntry.getKey(), headerEntry.getValue());
}
urlConnection.setConnectTimeout(5500);
urlConnection.setReadTimeout(5500);
urlConnection.setUseCaches(false);
urlConnection.setDoInput(true);
// Connect explicitly to avoid errors in decoders if connection fails.
urlConnection.connect();
if (isCancelled) {
return null;
}
final int statusCode = urlConnection.getResponseCode();
if (statusCode / 100 == 2) {
return getStreamForSuccessfulRequest(urlConnection, inputStreamReadCallback);
} else if (statusCode / 100 == 3) {
String redirectUrlString = urlConnection.getHeaderField("Location");
if (TextUtils.isEmpty(redirectUrlString)) {
throw new IOException("Received empty or null redirect url");
}
URL redirectUrl = new URL(url, redirectUrlString);
return loadDataWithRedirects(redirectUrl, redirects + 1, url, headers);
} else {
if (statusCode == -1) {
throw new IOException("Unable to retrieve response code from HttpUrlConnection.");
}
throw new IOException("Request failed " + statusCode + ": " + urlConnection.getResponseMessage());
}
}
private InputStream getStreamForSuccessfulRequest(HttpURLConnection urlConnection, InputStreamReadCallback inputStreamReadCallback)
throws IOException {
if (TextUtils.isEmpty(urlConnection.getContentEncoding())) {
int contentLength = urlConnection.getContentLength();
//修改这里,对网络返回的InputStream做一个包装,并提供回调的接口
stream = ContentLengthReadCallbackInputStream.obtain(urlConnection.getInputStream(), contentLength, inputStreamReadCallback);
} else {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Got non empty content encoding: " + urlConnection.getContentEncoding());
}
stream = urlConnection.getInputStream();
}
return stream;
}
@Override
public void cleanup() {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
@Override
public String getId() {
return glideUrl.getCacheKey();
}
@Override
public void cancel() {
// TODO: we should consider disconnecting the url connection here, but we can't do so directly because cancel is
// often called on the main thread.
isCancelled = true;
}
}
</pre>
InputStream的包装类实现如下:
<pre>
public final class ContentLengthReadCallbackInputStream extends FilterInputStream {
private InputStreamReadCallback readCallback;
private final long contentLength;
private int readSoFar;
public static InputStream obtain(InputStream other, long contentLength, InputStreamReadCallback readCallback) {
return new ContentLengthReadCallbackInputStream(other, contentLength, readCallback);
}
ContentLengthReadCallbackInputStream(InputStream in, long contentLength, InputStreamReadCallback readCallback) {
super(in);
this.readCallback = readCallback;
this.contentLength = contentLength;
}
@Override
public synchronized int available() throws IOException {
return (int) Math.max(contentLength - readSoFar, in.available());
}
@Override
public synchronized int read() throws IOException {
return checkReadSoFarOrThrow(super.read());
}
@Override
public int read(byte[] buffer) throws IOException {
return read(buffer, 0 /*byteOffset*/, buffer.length /*byteCount*/);
}
@Override
public synchronized int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
return checkReadSoFarOrThrow(super.read(buffer, byteOffset, byteCount));
}
private int checkReadSoFarOrThrow(int read) throws IOException {
if (read >= 0) {
readSoFar += read;
} else if (contentLength - readSoFar > 0) {
throw new IOException("Failed to read all expected data"
+ ", expected: " + contentLength
+ ", but read: " + readSoFar);
}
if (readCallback != null) {
//实际网络读取数和总长度在这里回调到外部
readCallback.onRead(readSoFar, contentLength);
}
return read;
}
}
</pre>
在UI层更新进度时注意下,底层的回调是很快的,UI更新时做个间隔,例如30MS才更新一次不然会很卡的。
<code>Glide.with(context).using(new ImageUrlLoader(this)).load(new GlideUrl(picUrl))</code>通过这种方式就可以愉快的显示图片加载进度了: