【发布时间】:2014-03-25 06:58:21
【问题描述】:
我已经使用桌面在谷歌驱动器中上传了一个 apk 文件。
现在,当我单击我的 android 活动中的按钮时,我需要将该 apk 文件下载到我的 android SDCARD 中。如何做到这一点。
【问题讨论】:
标签: android google-drive-api google-drive-android-api
我已经使用桌面在谷歌驱动器中上传了一个 apk 文件。
现在,当我单击我的 android 活动中的按钮时,我需要将该 apk 文件下载到我的 android SDCARD 中。如何做到这一点。
【问题讨论】:
标签: android google-drive-api google-drive-android-api
首先,您必须使用RESTful API,因为您必须在 DRIVE_FILE 范围内打开 Drive。 GDAA 仅具有 FILE 范围,不会看到您的 Android 应用未创建的任何内容。
在 RESTful API 中,这是一个 3 步过程
在第 1 步和第 2 步中,使用页面底部的“试试看”游乐场来正确形成您的查询和字段选择。第 3 步在其他地方有详细记录。这是一些可能有帮助的断章取义的代码
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 很容易做到这一点。如果将其上传到网络上的应用与 Android 上的应用具有相同的应用 ID,则您的应用将已经可以访问该文件。在这种情况下,您可以使用query 功能来定位文件。
否则,您可以使用OpenFileActivity 并要求用户选择他们要下载的apk。
获得文件的 DriveId 后,您可以按照read contents 指南打开内容。
【讨论】: