1

I've already seen

Is it possible to check progress of URLconnection.getInputStream()? https://stackoverflow.com/a/20120451/5437621

I'm using the following code to download a file from internet:

try {
    InputStream is = new URL(pdfUrl).openStream();
    byte[] pdfData = readBytes(is);
    return pdfData;
} catch (IOException e) {
    e.printStackTrace();
    return null;
}

public byte[] readBytes(InputStream inputStream) throws IOException {

    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];

    int len = 0;
    while ((len = inputStream.read(buffer)) != -1) {
        byteBuffer.write(buffer, 0, len);
    }

    return byteBuffer.toByteArray();
}

Is there any method I can get the progress of the file being downloaded ?

The answers I have seen are using a while loop but I don't understand how to use it in this case.

EDIT:

I'm using this in AsyncTask:

protected byte[] doInBackground(String... url) {
        pdfUrl = url[0];

        try {
            InputStream is = new URL(pdfUrl).openStream();
            DownloadBytes downloadData = readBytes(is);
            byte[] pdfData = downloadData.getBytes();
            progress = downloadData.getProgress();
            return pdfData;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
}

How can I adjust publishProgress() in this method ?

mrid
  • 5,782
  • 5
  • 28
  • 71
  • That would be in your implementation of `readBytes()`, which your question does not show. If you switch to a more modern HTTP client API, you can use interceptors with OkHttp to monitor download progress. – CommonsWare Oct 09 '17 at 16:51
  • @CommonsWare sorry I missed, I've updated the question and added the code for `readBytes()` – mrid Oct 09 '17 at 16:57
  • 3
    Um, well, you already have the `while` loop. It is in your `readBytes()` method. In there, you can keep track of how much you have read, and you can use the `getContentLength()` method show in the answers to your first linked-to question to determine how big the overall download should be. – CommonsWare Oct 09 '17 at 17:00
  • @CommonsWare please check my updated question. I want to know how can I use `publishProgress()` ? – mrid Oct 09 '17 at 17:27
  • Um, well, if `readBytes()` is an `AsyncTask`, you could post some sort of `DownloadEvent` to `publishProgress()`, where each event has the total bytes to be downloaded along with the sum of what has been downloaded so far. Your `onProgressUpdate()` would then use that information to update your UI. – CommonsWare Oct 09 '17 at 17:37
  • @CommonsWare hey I still need some help. is there any way i can contact you ? (if you can help) – mrid Oct 09 '17 at 18:09
  • I offer office hours chats and other services via [the Warescription](https://commonsware.com/warescription). – CommonsWare Oct 09 '17 at 18:24

0 Answers0