如何获得使用REST API从Google驱动器下载文件的进度?

问题描述:

我正在使用此方法从Google下载文件开车.

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

我的代码:

        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?

回答我自己的问题,找到它

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);