在android下载大文件时如何处理中断?

时间:2012-08-13 10:28:07

标签: android

我必须从FTP服务器下载一个大型压缩文件(包含多个文件)。在下载过程中,如果用户或网络中断/暂停,则应保存已损坏的下载文件。之后,用户可以继续从破坏的位置下载相同的文件。

2 个答案:

答案 0 :(得分:3)

您可以使用DownloadManager类。

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

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

自API级别9以来可用于上课。

答案 1 :(得分: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子句以安全地处理流并确保关闭它们。为了便于阅读,这里省略了它们。

相关问题