简体   繁体   English

如何在我的 Android 应用中显示上传到 Google Drive 的进度?

[英]How to show uploading to Google Drive progress in my android App?

i have the following code我有以下代码

which is supposed to upload an image from my android device to my google Drive.这应该将图像从我的 android 设备上传到我的 google Drive。

  private void saveFileToDrive() {

      progressDialog = ProgressDialog.show(this, "", "Loading...");

    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          // File's binary content
          java.io.File fileContent = new java.io.File(fileUri.getPath());
          FileContent mediaContent = new FileContent("image/jpeg", fileContent);

          // File's metadata.
          File body = new File();
          body.setTitle(fileContent.getName());
          body.setMimeType("image/jpeg");

          File file = service.files().insert(body, mediaContent).execute();
          if (file != null) {
            showToast("Photo uploaded: " + file.getTitle());

            progressDialog.dismiss();
            //startCameraIntent();
          }
        } catch (UserRecoverableAuthIOException e) {
          startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    });
    t.start();
  }

The thing is the upload never ends.问题是上传永远不会结束。 That's weird as the image not too big这很奇怪,因为图像不太大

and I guess if I would have upload it via original Drive App, it would be done faster.我想如果我通过原始 Drive App 上传它,它会做得更快。

1) how can I show the upload progress? 1)如何显示上传进度?

2) how can I make a callback within the same Activity after the upload is done? 2)上传完成后如何在同一个Activity中进行回调?

Downloading file from Google Drive: 从Google云端硬盘下载文件:

  1. You can either use an AsyncTask in which you can obtain an inputstream from the url and write a while loop for reading each line and showing the downloaded data on a dialog as below. 您可以使用AsyncTask,您可以在其中从url获取输入流,并编写while循环以读取每一行并在对话框中显示下载的数据,如下所示。

     @Override protected Boolean doInBackground(FilesObject... files) { // getting an input Stream. HttpResponse resp = service.getRequestFactory() .buildGetRequest(new GenericUrl(file.SourceImageUrl)).execute(); fileSize = resp.getHeaders().getContentLength(); if (fileSize != -1) { fileSizeReadableString = DiskSpaceUtil.readableFileSize(fileSize); } InputStream is = resp.getContent(); // publishing the progress in a dialog. int completed = 0; while ((length = inputStream.read(buffer)) > 0) { if (!this.isCancelled()) { completed += length; fOutputStream.write(buffer, 0, length); publishProgress(completed); } else { fOutputStream.flush(); fOutputStream.close(); inputStream.close(); return; } } @Override protected void onProgressUpdate(Integer... values) { sendShowloader("Downloading file ... \\n" + DiskSpaceUtil.readableFileSize(number) + " of " + fileSizeReadableString); } 
  2. You can use the inherent Google Drive's Download Listeners which can be set with insert object. 您可以使用固有的Google云端硬盘下载监听器,可以使用插入对象进行设置。

Uploading File to Google Drive : 将文件上传到Google云端硬盘:

We can upload files to google drive using Google own implementation of MediaHttpUploaderProgressListener as below : 我们可以使用Google自己的MediaHttpUploaderProgressListener实现将文件上传到google驱动器,如下所示:

    { // ... Inside some thread

    java.io.File fil = new java.io.File(file.SourceImageUrl);
    InputStream is = new FileInputStream(fil);

    InputStreamContent mediaContent = new InputStreamContent(file.mimeType, is);
            mediaContent.setLength(fil.length());

    // File's metadata.
    File body = new File();
    body.setTitle(file.FileTitle);
    body.setMimeType(file.mimeType);
    body.setParents(parents);
    body.setDescription("Content Uploaded to "+ DriveName);
    // Inserting the Remote Resource into Google Drive
    File destFile = null;

    if(fil.length() > 5 * 1024 * 1024)
    {
        // Resumable Uploads when the file size exceeds a file size of 5 MB.
        // check link : 
        // 1) https://code.google.com/p/google-api-java-client/source/browse/drive-cmdline-sample/src/main/java/com/google/api/services/samples/drive/cmdline/DriveSample.java?repo=samples&r=08555cd2a27be66dc97505e15c60853f47d84b5a
        // 2) http://stackoverflow.com/questions/15970423/uploading-downloading-of-large-size-file-to-google-drive-giving-error

        Insert insert = mService.files().insert(body, mediaContent);
        MediaHttpUploader uploader = insert.getMediaHttpUploader();
        uploader.setDirectUploadEnabled(false);
        uploader.setProgressListener(new FileUploadProgressListener());
        destFile = insert.execute();

    }   
    else
    {
        // Else we go by Non Resumable Uploads, which is safe for small uploads.
        destFile = mService.files().insert(body, mediaContent).execute();
    }

    ... }

    // Now the implementation of FileUploadProgressListener which extends MediaHttpUploaderProgressListener

public static class FileUploadProgressListener implements MediaHttpUploaderProgressListener {

    public void progressChanged(MediaHttpUploader uploader) throws IOException {
      switch (uploader.getUploadState()) {
        case INITIATION_STARTED:
          postToDialog("Initiation Started");
          break;
        case INITIATION_COMPLETE:
          postToDialog("Initiation Completed");
          break;
        case MEDIA_IN_PROGRESS:
          // postToDialog("Upload in progress");
          postToDialog("Upload percentage: " + uploader.getProgress());
          break;
        case MEDIA_COMPLETE:
          postToDialog("Upload Completed!");
          break;

        case NOT_STARTED :
            postToDialog("Not Started!");
            break;
      }
    }
  }

只需先检查您的网络连接!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android:如何使我的应用记住Google云端硬盘授权? - Android: how to make my app remember Google Drive Authorization? 在我的Android应用中管理Google云端硬盘上的文件 - Managing files on Google Drive in my Android app 如何在android改造中上传文件时显示进度条 - How to show progress bar when uploading a file in android retrofit Android:显示实际的上传进度百分比 - Android: Show real uploading progress percentage 如何仅使用Google Android应用中的Google Drive API在Google云端硬盘上创建和编辑电子表格文件? - How do I create & edit a spreadsheet file on google drive using Google Drive APIs only from my Android app? Android Studio和Google Drive API(将视频上传到Google Drive) - Android Studio and Google Drive API (Uploading video to Google Drive) 如何将图像从我的Android应用程序上传到Google驱动器上的特定文件夹 - how to upload an image from my android app to a specific folder on google drive 我的Android应用中的Google云端硬盘返回错误400 - Google Drive Returning Error 400 in my Android app Google Drive Android API如何将音频文件上传到我的驱动器? 如何同步驱动器文件? - Google Drive Android API how to upload a audio file to my drive ? How to sync drive files? 将文件上传到 Google Drive? - uploading a file to Google Drive?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM