Android慢速文件下载

Android慢速文件下载,android,file-io,httpclient,Android,File Io,Httpclient,我正在我的android应用程序上下载。我正在使用本地网络连接,下载速度非常慢 以下是我正在使用的代码: URL url = new URL(ep.getFileURL()); File destFile = new File(<path to sd card file>); URLConnection uCon = url.openConnection(); InputStream is = uCon.getInputStream(); OutputStream os = new

我正在我的android应用程序上下载。我正在使用本地网络连接,下载速度非常慢

以下是我正在使用的代码:

URL url = new URL(ep.getFileURL());
File destFile = new File(<path to sd card file>);

URLConnection uCon = url.openConnection();
InputStream is = uCon.getInputStream();
OutputStream os = new FileOutputStream(destFile);

int progress = 0;
int lastProgress = 0;
int totalSize = uCon.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[4096];
int count = -1;
while((count = is.read(buffer)) != -1)
{
    os.write(buffer, 0, count);

downloadedSize = downloadedSize + count;
    progress = (int)(downloadedSize * 100.0 / totalSize);
    if(progress - lastProgress >= 5) {
        publishProgress(progress);
        lastProgress = progress;
    }
}

os.close();
URL=newurl(ep.getFileURL());
File destFile=新文件();
URLConnection uCon=url.openConnection();
InputStream=uCon.getInputStream();
OutputStream os=新文件OutputStream(destFile);
int progress=0;
int lastProgress=0;
int totalSize=uCon.getContentLength();
int downloadedSize=0;
字节[]缓冲区=新字节[4096];
整数计数=-1;
而((count=is.read(buffer))!=-1)
{
写操作(缓冲区,0,计数);
downloadedSize=downloadedSize+计数;
进度=(int)(下载大小*100.0/总大小);
如果(进度-最新进度>=5){
出版进度(progress);
lastProgress=进度;
}
}
os.close();
你发现什么问题了吗?多谢各位

编辑:

我使用您的建议测试了我的代码,结果如下:

# Download times tests # Without bufferedoutput Downloading file: 1 ms, Start download Downloading file: 179812 ms, Finished downloading 54687744 bytes Downloading file: end, 179813 ms With bufferedoutput Downloading file: 1 ms, Start download Downloading file: 178312 ms, Finished downloading 54687744 bytes Downloading file: end, 178313 ms With httpclient Downloading file: begin Downloading file: 1 ms, Start download Downloading file: 178241 ms, Finished downloading 54687744 bytes Downloading file: end, 178242 ms #下载时间测试# 无缓冲输出 下载文件:1毫秒,开始下载 下载文件:179812毫秒,完成下载54687744字节 下载文件:结束,179813毫秒 带缓冲输出 下载文件:1毫秒,开始下载 下载文件:178312毫秒,完成下载54687744字节 下载文件:结束,178313毫秒 使用httpclient 下载文件:开始 下载文件:1毫秒,开始下载 下载文件:178241毫秒,完成下载54687744字节 下载文件:结束,178242毫秒 所以,使用缓冲流或直接使用HttpClient不会改变任何事情

我还应该提到我的代码在一个AsyncTask中,所以publishProgress()实际上已经在一个单独的线程上运行了


谢谢您的帮助。

您应该用BufferedInputStream包装您的输入流。您可能会得到更多的几个字节的浅读,而缓冲流将缓解其中的一些问题。我会首先尝试,缓冲输入和输出流,以减少操作系统级的写入延迟


第二,我会注意你发布进度的方式。看起来您正在限制它出现的次数,但是您可能希望将下载移动到自己的可运行状态,并使用executor服务进行下载,还可能启动一个额外的线程来评估所有下载的进度,并根据需要触发进度消息

使用
HttpClient
而不是
URLConnection

您现在的速度是多少,您期望的速度是多少?如果你在质疑IO的速度,你首先应该做的是计时,这样你就可以知道你的改进是否有显著的不同。你在publishProgress()中做了什么?(一点代码可能会有帮助。)FileOutputStream可能也应该包装在BufferedOutputStream中。我猜这是Android中异步任务的一部分,因此publishProgress将在UI线程上对消息进行排队,而不会阻止下载。所以出版进度在这里可能不是问题。