Android项目之文件下载
来源:互联网 发布:网络优化培训费多少 编辑:程序博客网 时间:2024/04/19 11:27
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(); } }
0 0
- Android项目之文件下载
- android 之文件下载
- Android之文件下载
- Android之文件下载
- Android之文件下载
- Android之文件下载
- android 之文件下载
- Android之文件下载
- android之文件下载
- Android之文件下载
- android开发步步为营之67:使用android开源项目android-async-http异步下载文件
- Android开发之文件下载
- android 开发之文件下载
- Android文件下载之断点续传
- Android之网络文件下载
- Android开发之文件下载
- [转]android 之文件下载
- android示例之文件下载
- 2017年2月20日实习日记
- 欢迎使用CSDN-markdown编辑器
- Butterknife源码
- Linux下informix安装及数据库迁移
- 第3章 XML语义检索
- Android项目之文件下载
- 分离mybatis的mapper.java和mapper.xml文件
- NOIP 提高组第一式第一题——玩具迷题
- exe4j生成的exe反编译成java代码
- java 中LinkedList详解,附带一部分源码和ArrayList的比较
- Python机器学习算法速查
- 1.6:继承
- 用Spark学习矩阵分解推荐算法
- 常见C++面试题及基本知识点总结(一)