Android 断点续传下载

断点续传下载,其实就是记录下原来下载的位置,然后从那个位置开始下载就是了。

代码如下。

/**
	 * 作用:断点续传下载<BR>
	 * 作者:peijiangping<BR>
	 * 日期:2011-6-11
	 */
	public static int doDownloadTheFile_test(String strPath, String filePath,
			String filename, int mode, long size, Handler handler) {
		//file.size()即可得到原来下载文件的大小
		//下载路径
		String url = strPath;
		// 设置代理
		Header header = null;
		if (mode == 2) {
			//移动内网的时候使用代理
			url = format_CMWAP_URL(strPath);
			header = new BasicHeader("X-Online-Host",
					format_CMWAP_ServerName(strPath));
		}
		HttpResponse response = null;
		// 用来获取下载文件的大小
		HttpResponse response_test = null;
		try {
			HttpClient client = new DefaultHttpClient();
			HttpClient client_test = new DefaultHttpClient();
			HttpGet request = new HttpGet(url);
			HttpGet request_test = new HttpGet(url);
			if (header != null) {
				request.addHeader(header);
			}
			response_test = client_test.execute(request_test);
			//获取需要下载文件的大小
			long fileSize = response_test.getEntity().getContentLength();
			// 验证下载文件的完整性
			if (fileSize != 0 && fileSize == size) {
				return 1;
			}
			//设置下载的数据位置XX字节到XX字节
			Header header_size = new BasicHeader("Range", "bytes=" + size + "-"
					+ fileSize);
			request.addHeader(header_size);
			response = client.execute(request);
			InputStream is = response.getEntity().getContent();
			if (is == null) {
				throw new RuntimeException("stream is null");
			}
			SDCardUtil.createFolder(filePath);
			//获取文件对象,开始往文件里面写内容
			File myTempFile = new File(filePath + "/" + filename);
			RandomAccessFile fos = new RandomAccessFile(myTempFile, "rw");
			//从文件的size以后的位置开始写入,其实也不用,直接往后写就可以。有时候多线程下载需要用
			fos.seek(size);
			byte buf[] = new byte[1024];
			long downloadfilesize = 0;
			do {
				int numread = is.read(buf);
				if (numread <= 0) {
					break;
				}
				fos.write(buf, 0, numread);
				if (handler != null) {
					Message msg = new Message();
					downloadfilesize += numread;
					double percent = (double) (downloadfilesize + size)
							/ fileSize;
					msg.obj = String.valueOf(percent);
					handler.sendMessage(msg);// 更新下载进度百分比
				}
			} while (true);
			is.close();
		} catch (Exception ex) {
			ex.printStackTrace();
			return -1;
		}
		return 1;
	}


上一篇:python常用模块之time&datetime模块


下一篇:Android--多线程断点续传