【发布时间】:2012-03-04 15:51:10
【问题描述】:
在我的 Android 应用程序中,我需要下载一个约 40 MB 的文件,我正在手机中测试代码,但下载速度真的很慢,我尝试从使用我的 PC 时快速的不同来源下载。
这是我在下载服务中使用的代码:
URLConnection conexion;
URL url;
int lenghtOfFile = 0;
try {
url = new URL("<URL>");
conexion = url.openConnection();
conexion.connect();
lenghtOfFile = conexion.getContentLength();
try {
File f = new File(Environment.getExternalStorageDirectory() + "/testing");
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(f.getAbsolutePath());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
notification.contentView.setProgressBar(R.id.status_progress, 100, (int) (total * 100 / lenghtOfFile), false);
notification.contentView.setTextViewText(R.id.status_text, Long.toString(total * 100 / lenghtOfFile));
notificationManager.notify(42, notification);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.getCause();
e.getMessage();
}
} catch (Exception e) {
}
}
这个代码有可能是 dl 速度慢的原因吗?关于如何使下载速度更快的任何想法?
【问题讨论】:
-
尝试增加缓冲区大小,它会减少I/O操作的数量,可以让你的应用程序运行得更快。
-
减少更新 ui 的频率,例如每十次迭代,也可能会提高性能。
-
您也可以线程 UI 更新,优先级较低。
-
已经列出了一些好的答案,所以我会横向思考一下,问有没有什么办法可以减小文件的大小?可以压缩吗?你可以只发送你需要的文件片段吗?等等等等。
-
@PaulGrime 这是我能得到的最小尺寸。它们已经被压缩了。感谢您的评论。