开发者

Android slow file download

I am downloading on my android app. I am using a local network connection and the download is really slow.

Here's he code I am using:

URL url = new URL(ep.getFileURL());
File destFile = new File(开发者_StackOverflow中文版<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();

Do you spot any problems? thank you.

Edit:

I tested my code using your suggestions and I got these results:

# 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

So, using Buffered streams or using HttpClient directly, doesn't change anything...

I also should have mentioned that my code is inside a AsyncTask, so publishProgress() actually runs on a separated thread already...

Thank you for your help.


You should wrap your input stream with a BufferedInputStream. You're probably getting a lot more shallow reads of a few bytes and a buffered stream will alleviate some of that. I would try that first, buffering both the input and output streams to reduce the OS level write delays.

Second, I'd be careful with how you are posting progress. It looks like you are limiting the number of times it comes up, but you might want to move the download into its own runnable and use an executor service for the download and maybe start an additional thread which evaluates the progress of all downloads and fires progress messages as necessary.


Use HttpClient instead of URLConnection

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜