Search code examples
androidgoogle-drive-apigoogle-drive-android-api

How to get progress of a file being downloaded from google drive using REST API?


I'm using this method to download a file from Google Drive.

My code:

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        driveService.files().export(remoteFiles[0].getId(),"text/plain").executeMediaAndDownloadTo(byteArrayOutputStream);


        FileOutputStream fileOutputStream= new FileOutputStream(new File(downloadsDirectory,remoteFiles[0].getName()));


        byteArrayOutputStream.writeTo(fileOutputStream);

        byteArrayOutputStream.flush();

        byteArrayOutputStream.close();
        fileOutputStream.close();

Is there a way to get the progress of the file download?


Solution

  • Answering my own question,found it on this page.

    //custom listener for download progress
    class DownloadProgressListener implements MediaHttpDownloaderProgressListener{
    
    
        @Override
        public void progressChanged(MediaHttpDownloader downloader) throws IOException {
            switch (downloader.getDownloadState()){
    
                //Called when file is still downloading
                //ONLY CALLED AFTER A CHUNK HAS DOWNLOADED,SO SET APPROPRIATE CHUNK SIZE
                case MEDIA_IN_PROGRESS:
                    //Add code for showing progress
                    break;
                //Called after download is complete
                case MEDIA_COMPLETE:
                    //Add code for download completion
                    break;
             }
        }
    }
    
    
    //create a Drive.Files.Get object,
    //set a ProgressListener
    //change chunksize(default chunksize seems absurdly high)
    Drive.Files.Get request = driveService.files().get(remoteFiles[0].getId());
    request.getMediaHttpDownloader().setProgressListener(new DownloadProgressListener()).setChunkSize(1000000);
    request.executeMediaAndDownloadTo(outputStream);