如何以编程方式在Android下载谷歌驱动器选择的文件?

时间:2016-02-02 12:23:32

标签: android download google-drive-api google-drive-android-api google-drive-realtime-api

Google广告选择代码如下:

private void initializeGoogleDrive() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Drive.API)
            .addScope(Drive.SCOPE_FILE)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

}

@Override
public void onConnected(Bundle bundle) {
    IntentSender intentSender = Drive.DriveApi
            .newOpenFileActivityBuilder()
            .setMimeType(new String[]{"text/plain", "text/html"})
            .build(mGoogleApiClient);
    try {
        startIntentSenderForResult(
                intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
    } catch (IntentSender.SendIntentException e) {
        Utility.appLog(TAG, "Unable to send intent");
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_OPENER) {
    if (resultCode == RESULT_OK) {
        DriveId driveId = (DriveId) data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
        String resourceId = driveId.getResourceId();
        String downloadUrl = "https://drive.google.com/open?id=" + resourceId + "&export=download";
        Utility.appLog(TAG, "Download Url :: " + downloadUrl);
    } 
}
}

我们可以获得下载网址,但遗憾的是,由于我在尝试下载文件时出现身份验证错误,无法下载。

提前致谢。

2 个答案:

答案 0 :(得分:1)

在Asynctask中执行此操作

try{
       URL url = new URL(URL);
       HttpURLConnection conn = (HttpURLConnection) url.openConnection();
       conn.setRequestMethod("GET");
       conn.setRequestProperty("Authorization", "OAuth " + GoogleAuthUtil.getToken(mContext, mCredential.getSelectedAccountName(), Constants.SCOPE));
       conn.setDoInput(true);
       // Starts the query
       conn.connect();
       int responseCode = conn.getResponseCode();
        //you will recive the file in input stream
        File sdcard = Environment.getExternalStorageDirectory();
            File file = new File(sdcard, "filename.ext");

            FileOutputStream fileOutput = new FileOutputStream(file);
            InputStream inputStream = conn.getInputStream();

            byte[] buffer = new byte[1024];
            int bufferLength = 0;

            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                fileOutput.write(buffer, 0, bufferLength);
            }
            fileOutput.close();
      }

我正在使用依赖项,

compile 'com.google.android.gms:play-services-identity:8.3.0'
    compile('com.google.api-client:google-api-client-android:1.20.0') {
        exclude group: 'org.apache.httpcomponents'
    }

答案 1 :(得分:0)

这里是下载驱动文件的代码

private val mExecutor: Executor = Executors.newSingleThreadExecutor()

需要指定下载文件的存放路径和要下载的文件的ID。 这是下载文件的方法

 fun downloadFile(targetFile: java.io.File?, fileId: String?): Task<Void?>? {
        return Tasks.call(mExecutor, {
            val outputStream: OutputStream = FileOutputStream(targetFile)
            mDriveService.files([fileId].executeMediaAndDownloadTo(outputStream)
            null
        })
    }