简体   繁体   中英

How to download google drive files using android api

The following program will display the "shared files with you" from google drive. i am displaying all the files in a listView, here i want to download the google drive file whenever a user clicks the list item and i have written a code to get file's drive id.

This is what i have done in the following code.

Please help me to download a file from google drive whenever a user clicks the list item using google drive android api.

public class MainActivity extends BaseDemoActivity{ 
private static final String TAG = "MainActivity";
private ListView mResultsListView;
private ResultsAdapter mResultsAdapter;
private ProgressBar mProgressBar;
private DriveId mSelectedFileDriveId;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mResultsListView = (ListView) findViewById(R.id.listViewSamples);
    mResultsAdapter = new ResultsAdapter(this);
    mResultsListView.setAdapter(mResultsAdapter);

    mResultsListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
                 if (mSelectedFileDriveId != null) {
                        open();
                        return;
                    }
            }


    });
}
private void open() {
    showMessage("Select files drive id = "+mSelectedFileDriveId);
    // Reset progress dialog back to zero as we're
    // initiating an opening request.
   // mProgressBar.setProgress(0);
    DownloadProgressListener listener = new DownloadProgressListener() {
        @Override
        public void onProgress(long bytesDownloaded, long bytesExpected) {
            // Update progress dialog with the latest progress.
            int progress = (int)(bytesDownloaded*100/bytesExpected);
            Log.d(TAG, String.format("Loading progress: %d percent", progress));
            mProgressBar.setProgress(progress);
        }
    };

    Drive.DriveApi.getFile(getGoogleApiClient(), mSelectedFileDriveId)
        .open(getGoogleApiClient(), DriveFile.MODE_READ_WRITE, listener)
        .setResultCallback(driveContentsCallback);
    mSelectedFileDriveId = null;

}

private ResultCallback<DriveContentsResult> driveContentsCallback =
        new ResultCallback<DriveContentsResult>() {
    @Override
    public void onResult(DriveContentsResult result) {
        if (!result.getStatus().isSuccess()) {
            showMessage("Error while opening the file contents");
            return;
        }
        showMessage("File contents opened");       
    }
};

/**
 * Clears the result buffer to avoid memory leaks as soon as the activity is no longer
 * visible by the user.
 */
@Override
protected void onStop() {
    super.onStop();
    mResultsAdapter.clear();
}

@Override
public void onConnected(Bundle connectionHint) {
    super.onConnected(connectionHint); 
   Drive.DriveApi.requestSync(getGoogleApiClient())
   .setResultCallback(statusCallback);
    showMessage("Connecting ...");
}

final private ResultCallback<Status> statusCallback =
        new ResultCallback<Status>() {
            @Override
            public void onResult(Status arg0) {
                // TODO Auto-generated method stub
             showMessage("Fetching...");
             if(arg0.getStatus().isSuccess()){
                 Query query = new Query.Builder()
                    .addFilter(Filters.sharedWithMe())
                    .build();

                 Drive.DriveApi.query(getGoogleApiClient(), query)
                 .setResultCallback(metadataCallback);
             }else{
                 showMessage("Error = "+arg0);
             }
        }
};

final private ResultCallback<DriveApi.MetadataBufferResult> metadataCallback = 
        new ResultCallback<DriveApi.MetadataBufferResult>() {
            @Override
            public void onResult(DriveApi.MetadataBufferResult result) {
                // TODO Auto-generated method stub
                showMessage("onResult ...");
                if (!result.getStatus().isSuccess()) {
                    showMessage("Problem while retrieving results");
                    return;
                }
                mResultsAdapter.clear();
                mResultsAdapter.append(result.getMetadataBuffer());
                MetadataBuffer buffer = result.getMetadataBuffer();
                Metadata meta = buffer.get(0);
                Log.v(TAG,"WEB CONTENT LINK = "+meta.getWebContentLink());
                mSelectedFileDriveId = (DriveId) meta.getDriveId();
                showMessage("Count = "+mResultsAdapter.getCount());
            }
        };  

}

Since there is not a specific method in the API to directly download the file, there are two workarounds to accomplish this:

a) Create a DriveFile object by calling the getFile() method. Then, opening the file using java.io.InputStream library, and converting this stream into a local file. More information on this resource: https://developers.google.com/drive/android/files

b) With the metadata WebContentLink, access that url either by an intent on your browser, or through a WebView. It is possible that you will require to authenticate again. Opening the file on the browser should prompt a download request.

Take a look at the Google Drive Android API sample in:

https://github.com/googledrive/android-demos

The RetrieveContentsActivity code shows you how to get the file content into a InputStreamReader.

To run the sample you will have to register a new app in

https://console.developers.google.com/

Enable the Google Drive API.

To use this API, you will need to create a new client ID in Credentials / OAuth (in Google Console).

You will need to generate SHA1 key using keytool and paste it there.

Windows example:

C:\Program Files\Java\jre1.8.0_40\bin>keytool -exportcert -alias androiddebugkey
 -keystore C:\Users\yourusername\.android\debug.keystore -list -v

More info here: https://developers.google.com/drive/android/files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM