Integrate Google Drive in Android

suggest change

Create a New Project on Google Developer Console

To integrate Android application with Google Drive, create the credentials of project in the Google Developers Console. So, we need to create a project on Google Developer console.

To create a project on Google Developer Console, follow these steps:

Enable Google Drive API

We need to enable Google Drive Api to access files stored on Google Drive from Android application. To enable Google Drive API, follow below steps:

Add Internet Permission

App needs Internet access Google Drive files. Use the following code to set up Internet permissions in AndroidManifest.xml file :

<uses-permission android:name="android.permission.INTERNET" />

Add Google Play Services

We will use Google play services API which includes the Google Drive Android API. So, we need to setup Google play services SDK in Android Application. Open your build.gradle(app module) file and add Google play services SDK as a dependencies.

dependencies {
  ....
    compile 'com.google.android.gms:play-services:<latest_version>'
  ....
}

Add API key in Manifest file

To use Google API in Android application, we need to add API key and version of the Google Play Service in the AndroidManifest.xml file. Add the correct metadata tags inside the tag of the AndroidManifest.xml file.

Connect and Authorize the Google Drive Android API

We need to 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.

/**
 * Called when the activity will start interacting with the user.
 * At this point your activity is at the top of the activity stack,
 * with user input going to it.
 */
@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();
    }

Disconnect Google Deive Android API

When activity stops, we will disconnected Google Drive Android API connection with Android application by calling disconnect() method inside activity’s onStop() method.

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

         // disconnect Google Android Drive API connection.
         mGoogleApiClient.disconnect();
    }
    super.onPause();
}

Implement Connection Callbacks and Connection Failed Listener

We will implement Connection Callbacks and Connection Failed Listener of Google API client in MainActivity.java file to know status about connection of Google API client. These listeners provide onConnected(), onConnectionFailed(), onConnectionSuspended() method to handle the connection issues between app and Drive.

If user has authorized the application, the onConnected() method is invoked. If user has not authorized application, onConnectionFailed() method is invoked and a dialog is displayed to user that your app is not authorized to access Google Drive. In case connection is suspended, onConnectionSuspended() method is called.

You need to implement ConnectionCallbacks and OnConnectionFailedListener in your activity. Use the following code in your Java 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;
        }

        /**
         *  The failure has a resolution. Resolve it.
         *  Called typically when the app is not yet authorized, and an  authorization
         *  dialog is displayed to the user.
         */

        try {

            result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);

        } catch (SendIntentException e) {

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

   /**
    * It invoked when Google API client connected
    * @param connectionHint
    */
    @Override
    public void onConnected(Bundle connectionHint) {

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

   /**
    * It invoked when connection suspended
    * @param cause
    */
    @Override
    public void onConnectionSuspended(int cause) {

        Log.i(TAG, "GoogleApiClient connection suspended");
    }

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents