use box-api progress listener

140 views Asked by At

I am trying to download a file from Box API application using their download function as stated here .

...
FileOutputStream stream = new FileOutputStream(info.getName());
// Provide a ProgressListener to monitor the progress of the download.
file.download(stream, new ProgressListener() {
   public void onProgressChanged(long numBytes, long totalBytes) {
    double percentComplete = numBytes / totalBytes;
 }
});
....

However I am unable to use the onProgessChanged function. Is there any examples as to how to access it? How do I access it?

1

There are 1 answers

0
Mebin Joe On

This is just a workaround. Create a class ProgressOutputStream by extending super class OutputStream.

public class ProgressOutputStream extends OutputStream {

        public ProgressOutputStream(long totalFileSize, OutputStream stream, Listener listener) {
            this.stream = stream;
            this.listener = listener;
            this.completed = 0;
            this.totalFileSize = totalFileSize;
        }

        @Override
        public void write(byte[] data, int off, int length) throws IOException {
            this.stream.write(data, off, length);
            track(length);
        }

        @Override
        public void write(byte[] data) throws IOException {
            this.stream.write(data);
            track(data.length);
        }

        @Override
        public void write(int c) {
            this.stream.write(c);
            track(1)
        }

        private void track(int length) {
            this.completed += length;
            this.listener.progress(this.completed, this.totalFileSize);
        }

        public interface Listener {
            public void progress(long completed, long totalFileSize);
        }
    }

Call ProgressOutputStream in your file.download() like:

FileOutputStream stream = new FileOutputStream(info.getName());
file.download(new ProgressOutputStream(size, stream, new ProgressOutputStream.Listener() {
    void progress(long completed, long totalFileSize) {
        // update progress bar here ...
    }
});

Give it a try. Hope this will give an idea.