[英]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.