最近一個項目中需要實現(xiàn)圖片加載時下載進度百分比的展示只洒。如果使用原始的HttpUrlConnection方式來加載圖片的話,實現(xiàn)起來就非常簡單了骚烧,直接讀取InputStream時將進度回調到上層即可。在Glide中有這樣的實現(xiàn)方式么肾请?網(wǎng)上查到的都是使用okhttp方式來加載的示例枚尼,其實用系統(tǒng)的HttpUrlConnection方式來加載也是能夠實現(xiàn)的贴浙。
因為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崎溃,完全代理掉網(wǎng)絡模塊。網(wǎng)上比較多的例子是通過okhttp方式來重寫網(wǎng)絡模塊盯质,但實際用什么網(wǎng)絡模塊是沒有任何關系的袁串。如何實現(xiàn)StreamModelLoader實際上在Glide源碼中也有非常多的例子。因為我實現(xiàn)的是單次請求時的網(wǎng)絡模塊替換呼巷,StreamModelLoader中的cache邏輯完全可以不用去理會囱修,關注核心點的接口就行了,簡單的實現(xiàn)如下:
<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) {
//這里簡單粗暴王悍,直接返回用于獲得網(wǎng)絡InputStream的DataFetcher破镰。內部才是真正讀網(wǎng)絡的邏輯,所以將讀網(wǎng)絡的回調傳進去
return new HttpUrlFetcher(model, inputStreamReadCallback);
}
}
</pre>
HttpUrlFetcher在Glide中有默認實現(xiàn)压储,我這里的實現(xiàn)跟它提供的沒有太多區(qū)別啤咽,唯一的區(qū)別就是將回調傳到InputStream中的Wrapper里面去,讓讀取網(wǎng)絡進度時能夠將進度回調出來渠脉。
<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();
//修改這里宇整,對網(wǎng)絡返回的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的包裝類實現(xiàn)如下:
<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) {
//實際網(wǎng)絡讀取數(shù)和總長度在這里回調到外部
readCallback.onRead(readSoFar, contentLength);
}
return read;
}
}
</pre>
在UI層更新進度時注意下芋膘,底層的回調是很快的鳞青,UI更新時做個間隔,例如30MS才更新一次不然會很卡的为朋。
<code>Glide.with(context).using(new ImageUrlLoader(this)).load(new GlideUrl(picUrl))</code>通過這種方式就可以愉快的顯示圖片加載進度了: