gpt4 book ai didi

Android - 如何将文件从 google drive 下载到 android SDCARD?

转载 作者:行者123 更新时间:2023-11-29 17:51:21 25 4
gpt4 key购买 nike

我已经使用桌面在 google drive 中上传了一个 apk 文件。

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

最佳答案

首先,您必须使用 RESTful API ,因为您必须在 DRIVE_FILE 范围内打开云端硬盘。 GDAA只有文件范围,不会看到您的 Android 应用程序未创建的任何内容。

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

  1. 使用LIST获取文件 URL(按“标题”查询)
  2. 使用GET (实际上是getContent())获取文件内容
  3. 获取二进制流并将其保存到您的 SD 卡

在第 1 步和第 2 步中,使用页面底部的“试用” Playground 来正确形成查询和字段选择。第 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 - 如何将文件从 google drive 下载到 android SDCARD?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22627428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com