我使用以下代码将图像下载到我的Android应用程序中:
private void download(URL url, File file) throws IOException {
Log.d(TAG, "download(): downloading file: " + url);
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedInputStream bufferStream;
OutputStream outputStream = null;
try {
bufferStream = new BufferedInputStream(inputStream, 512);
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[512];
int current;
while ((current = bufferStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, current);
}
} finally {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}
这段代码运行良好,但一些用户和测试人员抱怨照片不完整。我怀疑小网络的延迟会中断连接。
所以我想检测整个图像是否下载并保存的文件是完整的图像。有没有办法从bufferedinputstream中检测文件大小,或者有没有办法检测下载完成?
最佳答案
我建议使用Google Volley来提供一个超级简单的接口,用于一般的网络连接,特别是图像加载。它为您处理线程和批处理。
这是谷歌在谷歌游戏应用程序上使用的。
它将通过提供监听器来解决您的问题,监听器会在作业完成时通知您。