Android - 如何从谷歌驱动器下载文件到Android SDCARD?

时间:2014-03-25 06:58:22

标签: android google-drive-api google-drive-android-api

我已使用桌面在Google云端硬盘中上传了一个apk文件。

现在我需要在我的android活动中单击一个按钮时将该apk文件下载到我的android SDCARD中。如何实现这一点。

2 个答案:

答案 0 :(得分:3)

首先,您必须使用RESTful API,因为您必须在DRIVE_FILE范围内打开Drive。 GDAA只有FILE范围,不会看到您的Android应用未创建的任何内容。

在RESTful API中,这是一个3步骤的过程

  1. 使用LIST获取文件网址(通过'标题'查询)
  2. 使用GET(实际上是getContent())来检索文件内容
  3. 获取二进制流并将其保存到SD卡
  4. 在步骤1和2中,使用'尝试它'在页面底部的操场,以正确地形成您的查询和字段选择。其他地方有很好的记录。这里有一些可能有用的上下文代码

    com.google.api.client.googleapis.extensions
      .android.gms.auth.GoogleAccountCredential _crd  = 
      GoogleAccountCredential.usingOAuth2(this, Arrays.asList(DriveScopes.DRIVE_FILE));
    com.google.api.services.drive.Drive _svc =
    new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), _crd).build();
    
    // step 1: get the file list of files
    com.google.api.services.drive.model.FileList gooLst = 
     _svc.files().list().setQ( [YOUR_REQUEST_STRING])
        .setFields("items(title,downloadUrl)").execute();
    // get the URL from your list matching the title with the requested one
    
    // step 2: get the file contents 
    InputStream is = _svc.getRequestFactory()
     .buildGetRequest(new GenericUrl([URL_FROM_LIST]))
     .execute().getContent();
    
    // step 3: stream it to you file
    strm2File(is, [YOUR_FILE_NAME]);
    
    private void strm2File(InputStream inStrm, String flNm) {
      try {
        OutputStream outStrm = 
            new FileOutputStream(new java.io.File(_ctx.getExternalFilesDir(null), flNm));
        try {
          try {
            final byte[] buffer = new byte[1024];
            int read; 
            while (((read = inStrm.read(buffer)) != -1) && (!isCancelled()))
              outStrm.write(buffer, 0, read);
            outStrm.flush();
          } finally {outStrm.close();}
        } catch (Exception e) {}
        inStrm.close();
      } catch (Exception e) {}
    }
    

    上面代码中的步骤1和2必须位于非UI线程(如AsyncTask)中,并且必须实现许多错误处理( UserRecoverableAuthIOException ...)在它周围。

答案 1 :(得分:0)

使用新的Android API很容易实现。如果在网络上上传的应用的应用ID与Android上的相同,则您的应用已经可以访问该文件了。在这种情况下,您可以使用query功能找到该文件。

否则,您可以使用OpenFileActivity并要求用户选择要下载的apk。

获得文件的DriveId后,您可以打开read contents指南后面的内容。