Want create site? Find Free WordPress Themes and plugins.

In this article, I will explain you how to integrate Google Drive with an Android app, and how to download and read files stored on Google Drive through this Android app.

1-Create a new project in Android Studio.

2-Create a New Project on Google Developer Console.

Create the credentials of project in the Google Developers Console. To create a project on Google Developer Console, follow these steps:

google developer console

  • Create credentials to access API

create credentials to access api

  • Click on API Key option in the list to create API key.

create api key

  • Click on the Android Key to identify your Android Project. And add Package Name of the Android Project and SHA-1 fingerprint in the input fields to create API key.

android key

3- Enable Google Drive API

enable google drive api

4-Download Google.json file and add it into project inside app folder into your application.

5- Add internet permission in manifest in already created project.
<uses-permission android:name=”android.permission.INTERNET” />

6- Add Google play services dependencies in build.gradle.
compile ‘com.google.android.gms:play-services:11.0.4’

Also Read: Retrofit Android Example with Get and Post API Request.

7-Authenticate and connect Google Drive Android API
Authenticate and connect Google Drive Android API with Android application. Authorization of Google Drive Android API is handled by the GoogleApiClient. We will use GoogleApiClient within onResume() method.

@Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {

/**
* Create the API client and bind it to an instance variable.
* We use this instance as the callback for connection and connection failures.
* Since no account name is passed, the user is prompted to choose.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}

8-Disconnected Google Drive Android API connection
When activity stops, we will disconnected Google Drive Android API connection
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient != null) {

// disconnect Google Android Drive API connection.
mGoogleApiClient.disconnect();
}
super.onPause();
}
9-Implement Connection Callbacks and Connection Failed Listener

public class CreateEventActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {

private static final String TAG = “Google Drive Activity”;
private static final int REQUEST_CODE_OPENER = 2;
private GoogleApiClient mGoogleApiClient;
private DriveId mFileId;
public DriveFile file;

@Override
public void onConnectionFailed(ConnectionResult result) {

// Called whenever the API client fails to connect.
Log.i(TAG,”GoogleApiClient connection failed”+ result.toString());

if (!result.hasResolution()) {

// show the localized error dialog.
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}

try {

result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);

} catch (SendIntentException e) {

Log.e(TAG, &quot;Exception while starting resolution activity&quot;, e);
}
}

@Override
public void onConnected(Bundle connectionHint) {

Toast.makeText(getApplicationContext(), &quot;Connected&quot;, Toast.LENGTH_LONG).show();
}

@Override
public void onConnectionSuspended(int cause) {

Log.i(TAG, &quot;GoogleApiClient connection suspended&quot;);
}
}
10-Read Google Drive file
Check if Google Api client is connected. Then request to read file
if (mGoogleApiClient == null) {

mGoogleApiClient = new GoogleApiClient.Builder(CreateEventActivity.this)
.enableAutoManage(CreateEventActivity.this,CreateEventActivity.this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(CreateEventActivity.this)
.addOnConnectionFailedListener(CreateEventActivity.this)
.build();
}
else {
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(driveContentsCallback);
}
mGoogleApiClient.connect();

11-Request Callback
This callback method call openFileFromGoogleDrive method and send intent onActivityResult() method to handle result.

final ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
@Override
public void onResult(DriveApi.DriveContentsResult result) {

if (result.getStatus().isSuccess()) {
OpenFileFromGoogleDrive();
}
}
};

12-Method of OpenFileFromGoogleDrive
This method include request with all possible file formats to read from drive and it return result to intent to onActivityResult() method.

public void OpenFileFromGoogleDrive(){

IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[] { “text/html”, “application/zip”,”text/plain”,
“application/rtf”,”application/vnd.oasis.opendocument.text”,”application/pdf” ,
“application/vnd.openxmlformats-officedocument.wordprocessingml.document “,”application/epub+zip “,
“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”,
“application/x-vnd.oasis.opendocument.spreadsheet”,”text/csv”,”text/tab-separated-values”,
“application/zip”,”image/jpeg”,”image/png”,”application/vnd.google-apps.spreadsheet”,
“image/svg+xml”,”application/vnd.openxmlformats-officedocument.presentationml.presentation”,”application/vnd.oasis.opendocument.presentation”,
“application/vnd.google-apps.script+json”})
.build(mGoogleApiClient);
try {
startIntentSenderForResult(

intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);

} catch (IntentSender.SendIntentException e) {

Log.w(TAG, “Unable to send intent”, e);
}
}

13-onActivity Result Handler to handle response
In my case I am reading CSV file, which is same as reading CSV from device storage
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode==REQUEST_CODE_OPENER && resultCode==RESULT_OK){
DriveId mFileId = (DriveId) data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);

new Thread(){
@Override
public void run() {
DriveFile f = mFileId.asDriveFile();
DriveApi.DriveContentsResult result;
result = f.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null).await();
readCSVFile(result);
}
}.start();
}
}
}
14-Read File from result.
BufferedReader br=null;
try {
br = new BufferedReader(
new InputStreamReader(result.getDriveContents().getInputStream(),”UTF8″));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

String line = br.readLine();
Reading csv file in android app

Did you find apk for android? You can find new Free Android Games and apps.