2012-08-13 121 views
2

我必须从FTP服务器下载一个大的压缩文件(包含多个文件)。在下载过程中,如果用户或网络中断/暂停,则应保存损坏的下载文件。之后,用户可以从破坏的地方恢复下载相同的文件。如何在android下载大文件时处理中断?

+1

问题在哪里? – cjk 2012-08-13 10:29:23

+0

在标题我想。 :)。 Firefox在下载时保存文件。 IDM保存每个部分,然后在下载完成时进行确认。 – Shaiful 2012-08-13 10:30:39

+0

我需要android中的相同功能。 – Shafi 2012-08-13 10:58:22

回答

3

您可以使用DownloadManager类。

下载管理器是一个处理长时间运行的HTTP下载的系统服务。

检查http://developer.android.com/reference/android/app/DownloadManager.html

以上,因为API级别9

+0

即使关闭,我也想继续下载。 – Shafi 2012-08-13 10:44:13

+0

是否即使应用程序已关闭,下载应该继续吗?或其他东西 – 2012-08-13 10:46:20

+0

雅..如果应用程序已关闭,应保存下载的文件,以后再恢复下载相同的文件,从中断。 – Shafi 2012-08-13 10:52:22

0

一个可以设置字节的范围内使用Range HTTP头下载可用类。你所要做的就是记住你之前下载了多少个字节。 Apache的使用类别,它应该是这样的:

DefaultHttpClient = new DefaultHttpClient(); 
HttpGet httpGet = new HttpGet(youSourceUri); 

// That's the important part. Count represents the number of bytes already downloaded. 
// We leave the range open, so it will download 'till the end of the file. 
httpGet.addHeader(new BasicHeader("Range", "bytes=" + count + "-")); 

HttpResponse response = httpClient.execute(httpGet); 
HttpEntity entity = response.getEntity(); 
InputStream inputStream = entity.getContent(); 

// Then read from the input stream 

记得添加适当的try/catch/finally语句安全地处理流,并确保它们关闭。为了便于阅读,这里省略了它们。