Android - How to download the file from google drive to android SDCARD?

廉价感情. 提交于 2019-11-29 08:55:36
seanpj

First, you have to use the RESTful API, since you have to open Drive in a DRIVE_FILE scope. The GDAA has only FILE scope and will not see anything your Android app did not create.

In the RESTful API, it is a 3 step process

  1. use LIST to get the file URL (query by 'title')
  2. use GET (actually getContent()) to retrieve the file content
  3. get binary stream and save it to your SD card

In both step 1 and 2, use the 'try it' playground at the bottom of the pages to form your query and field selection correctly. Step 3 is well documented elsewhere. Here's some out-of-context code that may help

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) {}
}

Steps 1 and 2 in the code above have to be in the non-UI thread (like AsyncTask) and there is a lot of error handling that has to be implemented (UserRecoverableAuthIOException...) around it.

This is simple to accomplish using the new Android API. If the app that uploaded it on the web has the same app id as the one on Android, your app will already have access to the file. In that case you can use the query functionality to locate the file.

Otherwise, you can use the OpenFileActivity and ask the user to select the apk they want to download.

Once you have the DriveId of the file, you can open the contents following the read contents guide.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!