[英]Android - How to download the file from google drive to android SDCARD?
我使用桌面在谷歌驱动器上传了一个apk文件。
现在,当我点击我的android活动中的一个按钮时,我需要将该apk文件下载到我的android SDCARD中。 如何实现这一目标。
首先,您必须使用RESTful API ,因为您必须在DRIVE_FILE范围中打开Drive。 GDAA只有FILE范围,不会看到您的Android应用程序没有创建的任何内容。
在RESTful API中,它是一个3步骤的过程
在步骤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 ...)。
使用新的Android API很容易实现。 如果在网络上上传的应用的应用ID与Android上的相同,则您的应用已经可以访问该文件了。 在这种情况下,您可以使用查询功能来查找文件。
否则,您可以使用OpenFileActivity并要求用户选择要下载的apk。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.