- Android App: Preparing to Access Google Drive
- Android App: Setting up Google APIs Client Library for Java
- Android App: Connecting to Google Drive with Google APIs Client Library for Java
To get started using Google Drive with Google APIs Client Library for Java you need to connect using OAuth2. To do that requires calling GoogleAccountCredential.usingOAuth2(...) but first you need code similar to the following:
1
2
3
4
5
6
7
8
9
10
|
/**
* Request code for auto Google Play Services error
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
private static final int REQUEST_AUTHORIZATION = 1;
private static final int REQUEST_ACCOUNT_PICKER = 2;
private final HttpTransport m_transport = AndroidHttp.newCompatibleTransport();
private final JsonFactory m_jsonFactory = GsonFactory.getDefaultInstance();
private GoogleAccountCredential m_credential;
private Drive m_client;
|
Next in onCreate(...)
method you will need to call
GoogleAccountCredential.usingOAuth2(...) and then build the drive access as follows:
1
2
3
4
5
6
7
8
9
10
11
12
|
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
// Google Accounts using OAuth2
m_credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(DriveScopes.DRIVE));
m_client = new com.google.api.services.drive.Drive.Builder(
m_transport, m_jsonFactory, m_credential).setApplicationName("AppName/1.0")
.build();
...
}
|
You need to let the user select an account to which to connect through OAuth2, perhaps in a separate method:
1
2
3
|
...
startActivityForResult(m_credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
...
|
In the onResume()
method check if the user has selected an account:
1
2
3
4
5
6
|
...
if (m_credential.getSelectedAccountName() == null) {
// ask user to choose account
...
}
...
|
In the onActivityResult(...)
handle the result from the startActivityForResult
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
{
...
if ((requestCode == REQUEST_ACCOUNT_PICKER || requestCode == REQUEST_CODE_RESOLUTION)) {
if(resultCode == RESULT_OK) {
if(data != null && data.getExtras() != null) {
String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
m_credential.setSelectedAccountName(accountName);
...
}
}
// call method to start accessing Google Drive
...
} else { // CANCELLED
...
}
}
...
}
|
In a separate thread, which is needed to prevent the main thread from doing too much work, you can access Google Drive to create a folder, upload, and perform other Drive operations:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
...
File folder = new File();
folder.setTitle("A Folder");
folder.setMimeType("application/vnd.google-apps.folder");
Drive.Files.Insert folderInsert;
try {
folderInsert = m_client.files().insert(folder);
} catch (IOException e) {
e.printStackTrace();
}
try {
destFolder = folderInsert.execute();
} catch (IOException e) {
e.printStackTrace();
}
...
|
To create a folder inside another folder (subfolder):
1
2
3
4
|
Folder secondFolder = new File();
secondFolder.setTitle("Another Folder");
secondFolder.setMimeType("application/vnd.google-apps.folder");
secondFolder.setParents(Arrays.asList(new ParentReference().setId(destFolder.getId())));
|
The method to upload a file is straight from this post on Stack Overflow titled How to show uploading to Google Drive progress in my android App?:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
String TAG = "...";
String fileLocation = "...";
java.io.File fil = new java.io.File(fileLocation);
InputStream is = new FileInputStream(fil);
InputStreamContent mediaContent = new InputStreamContent(file.mimeType, is);
mediaContent.setLength(fil.length());
// File's metadata.
File body = new File();
body.setTitle(file.FileTitle);
body.setMimeType(file.mimeType);
body.setParents(parents);
body.setDescription("Content Uploaded to "+ DriveName);
// Inserting the Remote Resource into Google Drive
File destFile = null;
if(fil.length() > 5 * 1024 * 1024)
{
// Resumable Uploads when the file size exceeds a file size of 5 MB.
// check link :
// 1) https://code.google.com/p/google-api-java-client/source/browse/drive-cmdline-sample/src/main/java/com/google/api/services/samples/drive/cmdline/DriveSample.java?repo=samples&r=08555cd2a27be66dc97505e15c60853f47d84b5a
// 2) http://stackoverflow.com/questions/15970423/uploading-downloading-of-large-size-file-to-google-drive-giving-error
Insert insert = mService.files().insert(body, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(false);
uploader.setProgressListener(new FileUploadProgressListener());
destFile = insert.execute();
}
else
{
// Else we go by Non Resumable Uploads, which is safe for small uploads.
destFile = mService.files().insert(body, mediaContent).execute();
}
...
}
// Now the implementation of FileUploadProgressListener which extends MediaHttpUploaderProgressListener
public static class FileUploadProgressListener implements MediaHttpUploaderProgressListener {
public void progressChanged(MediaHttpUploader uploader) throws IOException {
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
Log.d(TAG,"Initiation Started");
break;
case INITIATION_COMPLETE:
Log.d(TAG,"Initiation Completed");
break;
case MEDIA_IN_PROGRESS:
// Log.d(TAG,"Upload in progress");
Log.d(TAG,"Upload percentage: " + uploader.getProgress());
break;
case MEDIA_COMPLETE:
Log.d(TAG,"Upload Completed!");
break;
case NOT_STARTED :
Log.d(TAG,"Not Started!");
break;
}
}
}
}
...
|
Available mime types that are supported by Google Drive can be found in the following links:
For more operations that can done using Google Drive:
And there you have it. A brief introduction on how to setup and use Google Drive.