Ravi Vyas
Ravi Vyas

Reputation: 12365

Android/Java slow network IO

I have an app in which I am trying to download a file. I am using HTTPUrlConnection for the download. Initially download speeds were way to slow.

I improved the performance by using a buffered input stream and increasing my buffer size from 1024 to 8192. Increasing the buffer beyond that did not lead to any improvement.

Here is a snippet :

InputStream inputStream = (InputStream) new URL(requestURL)
                    .getContent();
BufferedInputStream bufferedInputStream = new BufferedInputStream(
                    inputStream);
OutputStream outputStream = new FileOutputStream(fileSaveUrl);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
                    outputStream);    

int bytesToRead = 1024 * 256;
byte buffer[] = new byte[bytesToRead];
while ((count = bufferedInputStream.read(buffer)) != -1
    && !isCancelled()) {
        requestStatus((int) (downloaded * 100 / fileSize));
        bufferedOutputStream.write(buffer, 0, count);
}

Even after this, the same file downloads 2 times quicker on the iPad when compared to Android.

Am I missing something?

Edits

  1. Even before you ask/mention , the download is running on a separate thread. I do realize I do not need to buffer the output , but I will get around to that later :)
  2. About the bytesToRead : I was experimenting with different buffer sizes , last experiment was 256KB

Upvotes: 2

Views: 1433

Answers (2)

Ravi Vyas
Ravi Vyas

Reputation: 12365

The issue was that I was downloading and writing to the SD card on the same thread. Split the work into two threads using a Blocking queue buffer to improve the performance.

Upvotes: 2

Louis Ricci
Louis Ricci

Reputation: 21086

requestStatus((int) (downloaded * 100 / fileSize));

This could be one possible bottleneck. Updating a status in the same thread your doing work usually isn't a good idea. Your thread should be updating a volatile variable...

variable = (int) (downloaded * 100 / fileSize);

Then your UI thread should poll that variable to show progress.

Also, most cheap SD Cards are slow, writing to them will likely cause a slow down for large files.

Upvotes: 2

Related Questions