源码简介
实现android 上面多线程断点续传下载 ,支持暂停,记忆任务。
源码运行截图
源码片段
- try {
- HttpURLConnection http = (HttpURLConnection) downUrl
- .openConnection();
- http.setConnectTimeout(5 * 1000);
- http.setRequestMethod("GET");
- http.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg,application/x-shockwave-flash, application/xaml+xml,application/vnd.ms-xpsdocument, application/x-ms-xbap,application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword");
- // http.setRequestProperty(, null); // 设置客户端可以接受的返回数据类型
- http.setRequestProperty("Accept-Language", "zh-CN");
- http.setRequestProperty("Referer", downUrl.toString());// 设置请求的来源,便于对访问来源进行统计
- http.setRequestProperty("Charset", "UTF-8");
- // 计算该线程下载的开始位置
- int startPos = block * (threadId - 1) + downloadedLength;
- /**
- * 每块结束的位置(***一块需特殊处理,因为不能平均分配每块大下,***一块可能会有余数)
- */
- //int endPosition = (i + 1) != threadCount ? ((i + 1) * blockSize - 1): fileSize;
- // 计算该线程下载的结束位置
- int endPos = threadId!=threadCount? (block *threadId):fileSize;
- // 设置获取实体数据的范围,如果超过了实体数据的大小会自动返回实际的数据大小
- http.setRequestProperty("Range", "bytes=" + startPos + "-"+ endPos);
- // 客户端用户代理
- http.setRequestProperty("User-Agent",
- "Mozilla/4.0 (compatible; MSIE 8.0;"
- + " Windows NT 5.2; Trident/4.0;"
- + " .NET CLR 1.1.4322;"
- + " .NET CLR 2.0.50727;"
- + " .NET CLR 3.0.04506.30;"
- + " .NET CLR 3.0.4506.2152;"
- + " .NET CLR 3.5.30729)");
- // 使用长连接
- http.setRequestProperty("Connection", "Keep-Alive");
- // 获取远程连接的输入流
- InputStream inStream = http.getInputStream();
- // 设置本地数据缓存的大小为1M
- byte[] buffer = new byte[1024];
- // 设置每次读取的数据量
- int offset = 0;
- // 打印该线程开始下载的位置
- print("Thread " + this.threadId
- + " starts to download from position " + startPos);
- RandomAccessFile threadFile = new RandomAccessFile(
- this.saveFile, "rwd");
- // 文件指针指向开始下载的位置
- threadFile.seek(startPos);
源码链接:http://down.51cto.com/data/1980815