适用于Glide4.0.0--以下版本,因为using接口在4.0.0以上版本被删除了。
项目中需要新增 静态图片 和 动态图片的进度展示,尤其是动态图片。需要增加进度增加用户体验。
查看Glide文档并没有提供进度的接口,查看网上的文章需要重写Glide的网络获取途径,自己拿到输入流,交给Glide处理。
网上很多资料都是用的okhttp做的,创建拦截器,拦截输入流,进而拿到进度。但是项目里使用的Volly,看了看资料,Volly没有拦截器这种东西(粗略的查找),所以想到了使用HttpURLConnection这个超级底层的网络请求类处理输入流。
拿到输入流之后,读取总大小,并遍历读取获取到的输入流就可以拿到比例了。
Glide自己定义网络获取类,需要使用using接口
Glide.with(imageLoaderUtils.context).using(glideProcessShowLoader);
使用到的就是一个工厂模式的类,它会从一个固定回调里拿我们自定义的网络请求拿输入流的对象
@Overridepublic DataFetcher getResourceFetcher(String model,int width,int height) { return new GlideProgressDataFetcher(model,getImageLoaderUtils());}GlideProgressDataFetcher就是拿到使用HttpURLConnection获取输入流的类了,loadData回调会拿我们自己取得输入流,实现如下
@Override
public InputStream loadData (Priority priority)throws Exception {
try {
ByteArrayOutputStream baos = null;
baos = new ByteArrayOutputStream();
URL url = new URL(model);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6 * 1000);
conn.setRequestMethod("GET");
if (isCancel) {
return null;
}
if (conn.getResponseCode() == 200) {
final int size = conn.getContentLength();
inputStream = conn.getInputStream();
byte buffer[] = new byte[1024];
int len = 0;
int threadTotal = 0;
while ((len = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, len);
threadTotal += len;
if (imageLoaderUtils != null) {
final int finalThreadTotal = threadTotal;
final float progress = (float) finalThreadTotal / (float) size;
if (System.currentTimeMillis() - lastUpdateTime > 5 || progress > 0.95) {
lastUpdateTime = System.currentTimeMillis();
Tools.post(new Runnable() {
@Override
public void run() {
imageLoaderUtils.imageLoaderProgressListener.getProgressValue((float)
final ThreadTotal /(float) size);
}
});
}
}
}
baos.flush();
imageLoaderUtils.imageLoaderProgressListener.onProgressFinish();
return new ByteArrayInputStream(baos.toByteArray());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}这就是拿到 进度的过程了。 详细代码 请查看github