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

Drive REST API V3 Java Wrapper - upload with progress


I'm trying to upload a new file to a drive account using the V3 API and get upload progress. My current(working) code is the following:

 val fileMetadata = File()
        fileMetadata.name = newItemName
        fileMetadata.parents = mutableListOf(destFolder.remoteId)

        val osFile = java.io.File(filePath)
        val mediaContent = FileContent(getMimeType(filePath), osFile)

        val file = googleDriveService.files().create(fileMetadata, mediaContent)
                .setFields("*")
                .execute()

Is it possible to add some kind of a progress listener to a current solution or i need to use another service(like MediaHttpUploader)?


Solution

  • You may refer with this documentation which uses the CustomProgressListener class.

    class CustomProgressListener implements MediaHttpDownloaderProgressListener {
      public void progressChanged(MediaHttpDownloader downloader) {
        switch (downloader.getDownloadState()) {
          case MEDIA_IN_PROGRESS:
            System.out.println(downloader.getProgress());
            break;
          case MEDIA_COMPLETE:
            System.out.println("Download is complete!");
        }
      }
    }
    
    OutputStream out = new FileOutputStream("/tmp/driveFile.jpg");
    
    DriveFiles.Get request = drive.files().get(fileId);
    request.getMediaHttpDownloader().setProgressListener(new CustomProgressListener());
    request.executeMediaAndDownloadTo(out);
    

    Here are additional references you can use: