public void run() {
synchronized (cancelLock) {
if(isCancel) {
return;
} else {
isRunning = true;
}
}
File file = new File(filePath);
ImageDownloadListener.DownloadResult downloadResult;
if(file.exists()) {
downloadResult = ImageDownloadListener.DownloadResult.FILE_EXISTS;
} else {
if(url == null || url.trim().equals("")) {
downloadResult = ImageDownloadListener.DownloadResult.URL_EMPTY;
} else {
OutputStream outputStream = null;
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setRequestMethod("GET");
int responseCode = httpURLConnection.getResponseCode();
if(responseCode == 200) {
InputStream inputStream = httpURLConnection.getInputStream();
synchronized (lock) {
file.getParentFile().mkdirs();
file.createNewFile();
}
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length = -1;
int totalSize = httpURLConnection.getContentLength();
int currentSize = 0;
long lastNotify = System.currentTimeMillis();
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
currentSize += length;
if((System.currentTimeMillis() - lastNotify) > 200) {
new UiTaskProcess(totalSize, currentSize).execute();
lastNotify = System.currentTimeMillis();
}
}//此处有陷阱 如果文件流为空
outputStream.flush();
new UiTaskProcess(totalSize, currentSize).execute();
downloadResult = ImageDownloadListener.DownloadResult.SUCCESSFUL;
} else {
file.deleteOnExit();
downloadResult = ImageDownloadListener.DownloadResult.FAILED;
}
} catch (IOException e) {
e.printStackTrace();
if(outputStream != null)
try {
outputStream.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
file.delete();
downloadResult = ImageDownloadListener.DownloadResult.FAILED;
} finally {
closeQuietly(outputStream);
if(httpURLConnection != null)
httpURLConnection.disconnect();
}
}
new UiTaskResult(downloadResult).execute();
}
}
Android项目之文件下载
最新推荐文章于 2022-04-24 09:58:06 发布
本文介绍了一个图片下载任务的实现过程,包括使用同步锁确保线程安全、检查文件是否存在、处理URL有效性、设置HTTP请求参数、读取网络数据并写入本地文件等关键步骤。
8107

被折叠的 条评论
为什么被折叠?



