Android - 如何将文件从谷歌驱动器下载到 android SDCARD? [英] Android - How to download the file from google drive to android SDCARD?
问题描述
我已经使用桌面在谷歌驱动器中上传了一个 apk 文件.
I have uploaded an apk file in google drive using the desktop.
现在,当我单击我的 android 活动中的按钮时,我需要将该 apk 文件下载到我的 android SDCARD 中.如何做到这一点.
Now I need to download that apk file to in to my android SDCARD when I click on a button in my android activity. How to achieve this.
推荐答案
首先,你必须使用 RESTful API,因为您必须在 DRIVE_FILE 范围内打开云端硬盘.GDAA 只有 FILE 范围,不会看到您的 Android 应用未创建的任何内容.
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.
在 RESTful API 中,这是一个 3 步过程
In the RESTful API, it is a 3 step process
- use LIST to get the file URL (query by 'title')
- use GET (actually getContent()) to retrieve the file content
- get binary stream and save it to your SD card
在第 1 步和第 2 步中,使用页面底部的试试看"游乐场来正确形成您的查询和字段选择.第 3 步在其他地方有详细记录.这是一些可能有帮助的断章取义的代码
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) {}
}
上面代码中的第 1 步和第 2 步必须在非 UI 线程中(如 AsyncTask),并且必须实现很多错误处理(UserRecoverableAuthIOException...)围绕它.
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.
这篇关于Android - 如何将文件从谷歌驱动器下载到 android SDCARD?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!