【发布时间】:2015-07-18 05:42:27
【问题描述】:
我需要将几个大的 zip 文件下载到我的应用程序中(每个大约 25mb),但它看起来很慢(5 分钟以上),当我们在 iPad 上测试下载相同的文件时,它的下载速度要快几倍。我考虑过使用 Volley,但似乎 asynctask 最适合大文件(根据我的阅读)。
是否有人对我如何能够更快地下载/写入这些文件有任何建议或想法?
我目前的实现如下所示:
我的 AsyncTask 示例:
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
【问题讨论】:
标签: android download android-asynctask