【发布时间】:2016-09-01 04:30:57
【问题描述】:
我制作了一个显示图像列表的应用程序。但在此之前,我将所有图像下载到 sdcard,并显示一个包含下载文件数量的进度对话框。由于要下载许多图像,我正在考虑使用 Picasso 优化该过程。所以没有进度对话框。使用毕加索,我想在图像显示在 ImageView 之前将图像保存在我的应用程序目录中(作为正常下载的文件)。我想使用这段代码:
Picasso picassoInstance = new Picasso.Builder(context)
.downloader(new CustomDownloader(context, destination))
.build();
自定义下载器:
public class CustomDownloader extends OkHttpDownloader {
private File destination;
public CustomDownloader(Context context, File destination){
super(context);
this.destination = destination;
}
@Override
public Response load(Uri uri, boolean localCacheOnly) throws IOException {
Response response = super.load(uri, networkPolicy);
FileOutputStream fileOutput = new FileOutputStream(destination);
InputStream inputStream = response.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
return response;
}
}
最后,我使用这个语句在 ImageView 中加载图像:
picassoInstance.load(item.getItem().getPath()).resize(width,0).into(imageView);
我使用这种实现是否正确?或者你能提供另一种方式吗?
编辑 1:我使用上面的代码,但图像未显示在 ImageView 中,即使我看到 SDCARD 中下载的图像。
编辑 2:使用此代码,使用新线程:
@Override
public Response load(Uri uri, boolean localCacheOnly) throws IOException {
Response response = super.load(uri, networkPolicy);
new Thread(new Runnable() {
try {
FileOutputStream fileOutput = new FileOutputStream(destination);
InputStream inputStream = response.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch(IOException e){
e.printStackTrace();
}
}).start();
return response;
}
我在这行while ((bufferLength = inputStream.read(buffer)) > 0) 中有一个java.lang.ArrayIndexOutOfBoundsException: src.length=2048 srcPos=2048 dst.length=1024 dstPos=0 length=1024
【问题讨论】:
-
getPath()是文件的路径还是图片的URL?
-
这是网址。这个语句没有问题,因为我可以用静态 URL 来改变它