在android中,目前主流的加载图片基本都是用Glide框架。这个框架会自动的为我们处理网络加载与缓存图片的各种功能,而我们只需要给图片的地址与显示位置即可。但在加载图片的过程中我们无法知道当前加载的进度,所以我们需要对Glide进行扩展。
同理,我们先来看看效果:
现在我们正式开始吧
添加依赖
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.squareup.okhttp3:okhttp:3.9.0'
添加权限
<uses-permission android:name="android.permission.INTERNET" />
替换Glide里面网络通讯组件HTTP为OkHttp。
新建一个OkHttpFetcher类,并且实现DataFetcher接口,代码如下所示:
package cn.xie.fingerprinttest.http;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.util.ContentLengthInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* 将Glide中的HTTP通讯组件替换成OkHttp。
* @author xiejinbo
* @date 2019/11/12 0012 11:43
*/
public class OkHttpFetcher implements DataFetcher<InputStream> {
private final OkHttpClient client;
private final GlideUrl url;
private InputStream stream;
private ResponseBody responseBody;
private volatile boolean isCancelled;
public OkHttpFetcher(OkHttpClient client, GlideUrl url) {
this.client = client;
this.url = url;
}
@Override
public InputStream loadData(Priority priority) throws Exception {
Request.Builder requestBuilder = new Request.Builder()
.url(url.toStringUrl());
for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
String key = headerEntry.getKey();
requestBuilder.addHeader(key, headerEntry.getValue());
}
Request request = requestBuilder.build();
if (isCancelled) {
return null;
}
Response response = client.newCall(request).execute();
responseBody = response.body();
if (!response.isSuccessful() || responseBody == null) {
throw new IOException("Request failed with code: " + response.code());
}
stream = ContentLengthInputStream.obtain(responseBody.byteStream(),
responseBody.contentLength());
return stream;
}
@Override
public void cleanup() {
try