Free Android app covering all aspects of addiction, including prevention and treatment

Android apps and Google Drive: A tutorial

  • Written by  Clive

Using Google Drive in your apps

Google Play Services Drive tutorial icon

Google Drive is your storage in the sky.

You can use it like a local drive and access it from anywhere from any device.

Our tutorial shows you how to upload a text file from within your app to the user’s Google Drive. We also show you how to download the contents of the uploaded file.

It’s all about Google Play Services

Google Play Services has a whole bunch of services that you can use in your apps, services like:

  • Google Maps
  • Google Wallet
  • Google+
  • Google Drive

You can access these services from within your app; simply install the client library for the service that you want to use.

Google Play Services takes care of authorization so that your users are assured that their interaction with the Play Services are safe and secure.

Google Play Services Drive tutorial diagram

The device running your app must have Google Play Services installed

Users must have Google Play Services installed as it contains the various Google services. It runs in the background. The client library that you include in your app enables it to interact with the service.

Google Play Services is delivered through the Google Play store and is updated regularly so you get access to the latest service API’s.

Note that devices that don’t have the Google Play store app installed as well as devices running anything lower than Android 2.3 (Gingerbread) are not supported.

We’re going to be using the Google Drive service so we’ll have to include the Google Drive client library in our app.

The client library

You need to install the client library for each of the services that you want to access.

The libraries have the necessary interfaces enabling your apps to access the services. It also enables the user to get authorization to use these services using their credentials.

The client library is small so won’t affect the size of your app. You won’t need to upgrade the client library unless you want to access new features and products in the Play Services or to fix bugs.

As a developer, here are the steps that you need to follow if you want to include access to Google Drive in your apps.

Step 1

Set up Google Play Services

http://developer.android.com/google/play-services/setup.html

Step 2

Register your app in the Google Developer Console

https://developers.google.com/drive/android/get-started#get_an_android_certificate_and_register_your_application

Step 3

Build and run your app

Don’t forget to include the necessary permissions in the manifest.

Note

Some legal stuff

If you use the Google Drive Android API in your application, you must include the Google Play Services attribution text as part of a "Legal Notices" section in your application.

It’s recommended that you include legal notices as an independent menu item, or as part of an "About" menu item.

You can make a call to GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo() to get the attribution text at runtime.

Two-by-two: The cache

There are two versions of your file.

One version is saved in the device’s cache and the other in the cloud. The Android system takes care of the syncing for you but you have to ensure an internet connection.

You can work with the files offline and they’ll automatically sync when a connection is available.

The file to upload

Our text file that we upload to our Google Drive is in our device’s Download folder. You can put yours anywhere but then you’ll have to edit the code for the textFile in the UploadFileActivity activity’s onCreate() method.

Have you seen our tutorial, Using Android's file system for saving application data: Part 1. Saving files?

So here’s our tutorial app

Google Play Services Drive tutorial screenshot

The main activity displays two buttons. Press one to upload a text file to the user’s Google Drive and the other to download the file’s contents

We’ll show you how to upload a text file from a device to the user’s Google Drive. Then we’ll show you how to download the text file from the user’s Google Drive and display the text in a separate activity.

Ready, set, Go!

Getting a foot in the door: Building the GoogleApiClient

The GoogleApiClient interface is your main entry to the Google Play Services. So, the first thing that you need to do is get an instance of a GoogleApiClient.

Use the GoogleApiClient.Builder class to configure your GoogleApiClient.

A bare-bones configuration would include the following methods:

  • addApi() – where you specify which of the Google Play Services API’s are needed by your app
  • addScope() – this takes care of signing the user in using OAuth 2.0
  • addConnectionCallbacks() – register a listener to listen for connection events
  • addOnConnectionFailedListener() - register a listener to listen for failed connection events

Your activity will have to implement the two callbacks:

  • GoogleApiClient.ConnectionCallbacks
  • GoogleApiClient.OnConnectionFailedListener

Connecting to the service

Once you’ve built your GoogleApiClient, you’re ready to connect to the service.

So where do you call connect()?

Use the activity’s lifecycle methods to connect to and disconnect from the Google Play Services:

  • onCreate – do the initializing of the GoogleApiClient in the activity’s onCreate() method
  • onStart – connect the client to the Google Play Services in onStart()
  • onStop – disconnect the client from the Google Play Services in onStop()

On connecting

The connection callbacks

  • The onConnected() callback is triggered when a successful connection has been made. This is where you put your code to make your request to the Google Play Services, the Drive in our case

onConnected() runs asynchronously. The Bundle parameter contains data specific to the Play Services that you’re interacting with. It can be null if no content is provided

  • The onConnectionSuspended() callback is triggered when the client is temporarily disconnected. The GoogleApiClient will then automatically try to reconnect.

The cause parameter indicates the reason for the disconnection

The failed to connect callback

  • The onConnectionFailed() callback is triggered when the client fails to connect to the Google Play Services

The result parameter gives the reason for the failure. You can use the startResolutionForResult() method to try and reconnect if the user has resolved the cause of the failure. You then need to implement the onActivityResult() method in the activity to call connect() to connect to the service

Uploading the file

It’s a two-step process

Step 1

Get an instance of a new DriveContents object by calling the newDriveContents() method. We use the ResultCallback interface to receive the drive contents result asynchronously.

Step 2

Build your file, using the drive contents object as the foundation. We:

  • first get an output stream out of the drive contents
  • then we add our text file to the output stream
  • next we set the metadata for our new file
  • finally we call createFile(), passing the metadata and new drive contents as parameters, to create the new file in the given Drive folder

So how do we know that our create file operation was successful?

Use a ResultCallback to receive a DriveFileResult object. It contains a DriveFile object which gives us access to the file’s metadata and contents.

Here’s the code for the Upload activity

Downloading a Drive file’s contents

The first steps are the same as the last

Each time you interact with your Google Drive, you have to:

  • build your GoogleApiClient
  • connect the client to the service
  • ensure that you have the connection and failure callbacks

Proceed once connected: Getting your Google Drive file’s contents

So you’ve made the connection, now what…

Get a DriveId object

The first step is to get a DriveId object that you’ll need later to get the file contents. The DriveId identifies a Drive resource.

Use fetchDriveId() to get the DriveId object.

You need to pass the GoogleApiClient and the resource ID of the file whose contents you want to access, as parameters. So here’s the catch. The resource ID is only available once the file has been synced to the cloud drive. So if you’ve just uploaded a file to your Google Drive, it may only exist in the cache in which case it won’t have a resource ID.

There are ways of getting the resource ID’s of Google Drive files but for this example, we’re going to cheat a bit.

If you have a file resource ID, then set our EXISTING_FILE_ID constant’s vale to it. If you don’t have one, then open up your Google Drive on the web. Now right-click on a text file (for this example, it must be in the root folder), select Get link. A popup will appear with the link highlighted. Copy the id parameter value, this is the resource ID. Paste it as the value for our EXISTING_FILE_ID constant.

The result of the fetchDriveId() call is returned in the DriveIdResult callback, idCallback.

The idCallback result

The DriveId object is contained in the result. You can now get your file.

Get a DriveFile object

Call getFile(), passing the GoogleApiClient and drive id as parameters, to get a DriveFile object.

Get the file’s contents

Call open() on the DriveFile object. It will return the drive contents in a pending result.

Open the file

The pending result callback presents the file contents. We can then read the file, building a string as we do so.

Once we’re finished reading the file, we bundle the string into an intent and start an activity to display the text.

Here’s the code for the download file activity

I hope that you have found this tutorial useful.

Have you seen our other Google Drive tutorial? Android apps and Google Drive: Picking files.

You may also be interested in this tutorial: Android cloud connections using the OkHttp library.

You can download the rest of the code here download button