Working solution for newer Android versions:
String authToken = GoogleAuthUtil.getToken(context, userEmail, "oauth2:" + DriveScopes.DRIVE);
This approach works perfectly and allows me to build my Drive service and interact with Google Drive API. However, this method only works on Android 2.2+. My app needs to support Android 2.1 as well.
Alternative approach for older Android versions:
AccountManager manager = AccountManager.get(this);
Bundle params = new Bundle();
manager.getAuthToken(
userAccount,
"oauth2:" + DriveScopes.DRIVE,
params,
this,
new TokenCallback(this),
null);
This code successfully retrieves a token, but when I use it to build my Drive service, the API calls fail. For instance, when I try:
driveService.files().list().setQ("trashed=false and name='myFile'").execute();
I get this error:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
"code": 401,
"errors": [{
"domain": "global",
"location": "Authorization",
"locationType": "header",
"message": "Invalid Credentials",
"reason": "authError"
}],
"message": "Invalid Credentials"
}
My Drive service setup:
HttpTransport transport = new NetHttpTransport();
JacksonFactory factory = new JacksonFactory();
Drive.Builder builder = new Drive.Builder(transport, factory, null);
builder.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
public void initialize(JsonHttpRequest req) throws IOException {
DriveRequest driveReq = (DriveRequest) req;
driveReq.setPrettyPrint(true);
driveReq.setKey(API_KEY);
driveReq.setOauthToken(authToken);
driveReq.setEnableGZipContent(true);
}
});
driveService = builder.build();