2

Google drive selection code is below :

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);
    } 
}
}

we can get download url but unfortunately download can not be done because of authentication error occurred when i am trying to download file.

Thanks in advance.

patel
  • 830
  • 1
  • 11
  • 26

2 Answers2

1

Do this in 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();
      }

I'm using dependencies,

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'
    }
Madhur
  • 3,303
  • 20
  • 29
  • 1
    Please explain : mCredential.getSelectedAccountName() and mCredential.getSelectedAccountName() and how can i get from my above code? – patel Feb 02 '16 at 12:39
  • The name of the selected account check this out http://stackoverflow.com/questions/35098468/how-to-get-oauth-token-from-googleapiclient/35098661#35098661 – Madhur Feb 02 '16 at 12:39
  • I seen your link: In this link use GoogleAccountCredential and ExponentialBackOff class. any dependency use for this both class? – patel Feb 02 '16 at 12:43
  • 'com.google.android.gms:play-services-identity:8.3.0' – Madhur Feb 02 '16 at 12:45
  • yes you are right. Only 2 things that's i don't know : android 'ACC_NAME' and 'scope'. – patel Feb 02 '16 at 12:52
  • look at that link i have mentioned scope and acc_name will be selected account email id – Madhur Feb 02 '16 at 12:55
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/102358/discussion-between-patel-and-madhur). – patel Feb 02 '16 at 12:55
0

Here is the code for downloading the drive file

private val mExecutor: Executor = Executors.newSingleThreadExecutor()

You need to specify the path to store the downloaded file and ID of the file you want to download. Here is the method to download file

 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
        })
    }
Nadeem Aslam
  • 123
  • 1
  • 7
  • There's an alternative approach we can use (if using Kotlin already): https://nickskelton.medium.com/converting-firebase-api-callbacks-to-kotlin-flows-3eea87429ee9 – mochadwi Jul 28 '21 at 13:48