I refer from this code
AccountManager am = AccountManager.get(activity);
am.getAuthToken(am.getAccounts())[0],
"oauth2:" + DriveScopes.DRIVE,
new Bundle(),
true,
new OnTokenAcquired(),
null);
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
try {
final String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JSonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(CLIENT ID YOU GOT WHEN SETTING UP THE CONSOLE BEFORE YOU STARTED CODING)
driveRequest.setOauthToken(token);
}
});
final Drive drive = b.build();
final com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle("My Test File");
body.setDescription("A Test File");
body.setMimeType("text/plain");
final FileContent mediaContent = new FileContent("text/plain", an ordinary java.io.File you'd like to upload. Make it using a FileWriter or something, that's really outside the scope of this answer.)
new Thread(new Runnable() {
public void run() {
try {
com.google.api.services.drive.model.File file = drive.files().insert(body, mediaContent).execute();
alreadyTriedAgain = false; // Global boolean to make sure you don't repeatedly try too many times when the server is down or your code is faulty... they'll block requests until the next day if you make 10 bad requests, I found.
} catch (IOException e) {
if (!alreadyTriedAgain) {
alreadyTriedAgain = true;
AccountManager am = AccountManager.get(activity);
am.invalidateAuthToken(am.getAccounts()[0].type, null); // Requires the permissions MANAGE_ACCOUNTS & USE_CREDENTIALS in the Manifest
am.getAuthToken (same as before...)
} else {
// Give up. Crash or log an error or whatever you want.
}
}
}
}).start();
Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 3025);
return; // Not sure why... I wrote it here for some reason. Might not actually be necessary.
}
} catch (OperationCanceledException e) {
// Handle it...
} catch (AuthenticatorException e) {
// Handle it...
} catch (IOException e) {
// Handle it...
}
}
}
In jsonHttpRequestInitializer i get an issues. [GoogleClient$Builder cannot be resolved. It is indirectly referenced from required .class files] please suggest me what i have to do...
You have two different APIs you can use on Android, the REST and the GDAA.
REST is the 'barebones' API that gives you the full functionality of Google Drive. You also have an interactive playground to test everything (see the bottom of this page). But you have to manage the network delays, failures, etc... yourself. Ideally you would delegate that work to sync adapter service.
GDAA is built on top of REST, resides in Google Play Services and behaves as a local API with delayed promotion of objects (folders/files) to the Drive. Has only limited functionality compared to REST (forget thumbnail link, etc...). Essentially, you talk to GDAA and GDAA talks to the Drive on it's own schedule. So, you don't have to worry about on-line / off-line situations. Be careful though, this may also cause synchronization issues, since you don't have direct control over object promotion timing. The demos for GDAA can be found here and here.
I've also created a simple CRUD demo app that you can step through. The upload you're asking resides in create() method there. It is not fully up-to-date, since GDAA has implemented the 'trash' functionality already (in Google Play Services 7.00 / Rev. 23).
Good Luck
Related
I am trying to develop an app wherein I am using Google Drive to upload and share of file in service. However, the problem is that shared link has private access. I want to change that access to anyone with link. To achieve that I am using Google Drive REST API, however nothing seems to happen when I execute the code. Here is my code:
public void changePermissionSettings(String resourceId) throws GeneralSecurityException, IOException, URISyntaxException {
com.google.api.services.drive.Drive driveService = getDriveService();
JsonBatchCallback<Permission> callback = new JsonBatchCallback<com.google.api.services.drive.model.Permission>() {
#Override
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException {
Log.e("upload", "Permission Setting failed");
}
#Override
public void onSuccess(com.google.api.services.drive.model.Permission permission, HttpHeaders responseHeaders) throws IOException {
Log.e("upload", "Permission Setting success");
}
};
final BatchRequest batchRequest = driveService.batch();
com.google.api.services.drive.model.Permission contactPermission = new com.google.api.services.drive.model.Permission()
.setType("anyone")
.setRole("reader");
driveService.permissions().create(resourceId, contactPermission)
.setFields("id")
.queue(batchRequest, callback);
new Thread(new Runnable() {
#Override
public void run() {
try {
batchRequest.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private com.google.api.services.drive.Drive getDriveService() throws GeneralSecurityException,
IOException, URISyntaxException {
Collection<String> elenco = new ArrayList<>();
elenco.add("https://www.googleapis.com/auth/drive");
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(this, elenco)
.setSelectedAccountName(getAccountName());
return new com.google.api.services.drive.Drive.Builder(
AndroidHttp.newCompatibleTransport(), new JacksonFactory(), credential).build();
}
I have two questions here:
Is it right to use both Google Drive Android API and Google Drive REST API together??
How to change permission setting of file from private to anyone with link?? Documentation mentions that Authorization happens in response to receiving an error when sending a request. How can that be achieved in service??
"Is it right to use both Google Drive Android API and Google Drive REST API together??"
As stated here, it is possible. "Just looking at the this Lifecycle of a Drive file, you can imagine your app on top of that picture (Android App) and the REST API on the bottom (Drive Service)."
There is a few points to keep in mind, though:
The GDAA's main identifier, the DriveId lives in GDAA (GooPlaySvcs) only and does not exist in the REST Api. You must retrieve 'ResourceId' which is the main identifier in the REST Api (see SO 29030110).
ResourceId can be obtained from the DriveId only after GDAA committed (uploaded) the file/folder (see SO 22874657)
You will run into a lot of timing issues caused by the fact that GDAA 'buffers' network requests on it's own schedule (system optimized), whereas the REST Api let your app control the waiting for the response. In general, if you scan these SO questions, you'll find a lot of chatter about these issues (it's a mess, though).
I maintain a minimal CRUD wrappers for both GDAA and the REST API that can help you if you merge them (the MainActivity in both of them is almost identical and the CRUD methods have the same signatures).
"How to change permission setting of file from private to anyone with link?? Documentation mentions that Authorization happens in response to receiving an error when sending a request. How can that be achieved in service??"
Based from this thread, you have to set the following permissions:
private Permission insertPermission(Drive service, String fileId) throws Exception{
Permission newPermission = new Permission();
newPermission.setType("anyone");
newPermission.setRole("reader");
newPermission.setValue("");
newPermission.setWithLink(true);
return service.permissions().insert(fileId, newPermission).execute();
}
You can also check this link: Google Drive SDK - change item sharing permissions.
My Android app should offer the functionality of sharing files via google drive:
1) upload a file (which was selected previously from the sd-card) to google drive
2) get back a link (url) to the uploaded file
3) share this link with other users of the app
4) other users may download the shared file to the sd-card of their device
All this functionality should be available in the app, without having the need to use a browser.
Does anyone have an idea how i can implement the steps 1, 2 and 4?
thanks in advance!
gerhard
This can help you for Google Drive file upload -
First, go for authentication
AccountManager am = AccountManager.get(activity);
am.getAuthToken(am.getAccounts())[0],
"oauth2:" + DriveScopes.DRIVE,
new Bundle(),
true,
new OnTokenAcquired(),
null);
Now need to set token
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
try {
final String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JSonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(CLIENT ID YOU GOT WHEN SETTING UP THE CONSOLE BEFORE YOU STARTED CODING)
driveRequest.setOauthToken(token);
}
});
final Drive drive = b.build();
final com.google.api.services.drive.model.File body = new
com.google.api.services.drive.model.File();
body.setTitle("My Test File");
body.setDescription("A Test File");
body.setMimeType("text/plain");
final FileContent mediaContent = new FileContent("text/plain",
"Your data")
new Thread(new Runnable() {
public void run() {
try {
com.google.api.services.drive.model.File file =
drive.files().insert(body, mediaContent).execute();
alreadyTriedAgain = false;
} catch (IOException e) {
if (!alreadyTriedAgain) {
alreadyTriedAgain = true;
AccountManager am = AccountManager.get(activity);
am.invalidateAuthToken(am.getAccounts()[0].type, null); // Requires the permissions MANAGE_ACCOUNTS & USE_CREDENTIALS in the Manifest
am.getAuthToken (same as before...)
} else {
// Give up. Crash or log an error or whatever you want.
}
}
}
}).start();
Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 3025);
return; // Not sure why... I wrote it here for some reason. Might not actually be necessary.
}
} catch (OperationCanceledException e) {
// Handle it...
} catch (AuthenticatorException e) {
// Handle it...
} catch (IOException e) {
// Handle it...
}
}
}
Now, To update the file
public void updateFile(Drive drive, File gFile, java.io.File jFile) throws
IOException {
FileContent gContent = new FileContent("text/csv", jFile);
gFile.setModifiedDate(new DateTime(false, jFile.lastModified(), 0));
gFile = drive.files().update(gFile.getId(), gFile,
gContent).setSetModifiedDate(true).execute();
}
Also, Don't fget to give permissions in Manifest for
GET_ACCOUNTS, USE_CREDENTIALS, MANAGE_ACCOUNTS, INTERNET WRITE_EXTERNAL_STORAGE
I want to design an Android file viewer for Google Drive.
At first, I implemented the app by using of the Google Android API, as follows,
private void retrieveNextPage(){
if(mHasMore == false)
return;
Query query = new Query.Builder().setPageToken(mNextPageToken).build();
com.google.android.gms.drive.Drive.DriveApi.query(getGoogleApiClient(), query).setResultCallback(metadataBufferResultResultCallback);
}
However, the Android Drive API only allows the app to view and fetch the files that created by itself. I cannot access other files on the drive through the app.
Therefore, I turned to another option, directly manipulate the Java Drive API.
According to the example on developer guide for Java,
https://developers.google.com/drive/web/quickstart/quickstart-java
The users have to manually copy and paste the "Authorization Code" between the browser and app, which is not a practical way to acquire the Access Token in Android.
To come out a new way, I used the GoogleAuthUtil in Android API to acquire the Access Token, coincided with the GoogleCredential and Drive in Java API to fetch the file list, as follows,
private static List<File> retrieveFiles(Drive service) throws IOException{
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try{
FileList fileList = request.execute();
result.addAll(fileList.getItems());
request.setPageToken(fileList.getNextPageToken());
}catch (IOException e){
Log.d(dbgT + "JavaRetrieveFiles", "Retrieved Failed");
request.setPageToken(null);
}
}while (request.getPageToken() != null && request.getPageToken().length() > 0);
return result;
}
private class RetrieveTokenTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params){
String accountName = params[0];
String scopes = "oauth2:" + "https://www.googleapis.com/auth/drive";
String token = null;
try{
token = GoogleAuthUtil.getToken(getApplicationContext(), accountName, scopes);
}
catch (IOException e){
Log.e(excpTAG, "IO Exception: " + e.getMessage());
}
catch (UserRecoverableAuthException e){
startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED);
}
catch (GoogleAuthException e)
{
Log.e(excpTAG, "GoogleAuthException: " + e.getMessage());
}
return token;
}
#Override
protected void onPostExecute(String s){
super.onPostExecute(s);
//Get Access Token
Log.d( dbgT + "Token", s);
EditText tokenText = (EditText) findViewById(R.id.tokenText);
tokenText.setText(s);
EditText fileNameText = (EditText) findViewById(R.id.editTextMeta);
GoogleCredential credential = new GoogleCredential().setAccessToken(s);
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null).setHttpRequestInitializer(credential).build();
List<File> fileList;
try{
fileList = retrieveFiles(service);
for(int i=0; i< fileList.size(); i++)
fileNameText.append(fileList.get(i).getTitle());
}catch(IOException e){
Log.d(dbgT + "RetrieveFileList", "IO Exception" );
}
}
}
Unfortunately, the app always crashes by the causing of NetworkOnMainThreadException when request.execute() in retrieveFiles is invoked.
I checked my access token s, it is usually in form of ya29.xxx...etc., and it can also be passed to my other .NET program for retrieving files from Google Drive. Therefore I can certain the access token is correct.
So my question is, how to create a correct GoogleCredential by using of access token, instead of applying authorization code in setFromTokenResponse ?
Thanks in advance.
Many thanks for Andy's tips, this problem is simply caused by the network operations occurs on the main thread, which is a very basic newbie error.
The Drive in Google Drive SDK for Java, using network libraries without any background/thread worker, and now it is functional after I put the retrieveFiles() into background.
Applying the GoogleAuthUtil in Google Play Android SDK to acquire the access token, and followed by GoogleCredential+Drive in Java SDK that use the token to do the file operation in Google Drive.
This is a right way to avoid the scope restriction in Android SDK for Google Drive, allowing the developers to acquire the full permissive of accessing Google Drive.
I'm trying to do an Android app that needs to work with Google spreadsheet API. I'm new in this, so I'm starting with the version 3 of the api: https://developers.google.com/google-apps/spreadsheets/
I followed all the steps, downloaded all the jar files to lib subfolder in my project folder and then I added to the build path in Eclipse as usual. So although there is no Java example to perform Oauth 2.0, I just tried to declare:
SpreadsheetService service = new SpreadsheetService("v1");
but when I emulate this simple line it gives me an error:
java.lang.NoClassDefFoundError: com.google.gdata.client.spreadsheet.SpreadsheetService
I'm using all the jars included in the documentation and I have the import:
import com.google.gdata.client.spreadsheet.SpreadsheetService;
but I am totally lost. I dont know what else to do just to start, connect to Google APIs and work with the spreadsheets.
Sample code for you without OAuth 2.0. But its recommended to perform OAuth as its good for the security purpose. You also have to add below permissions.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCOUNT_MANAGER"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Sample Code:-
try {
SpreadsheetEntry spreadsheet;
service = new SpreadsheetService("Spreadsheet");
service.setProtocolVersion(SpreadsheetService.Versions.V3);
service.setUserCredentials("username", "password");//permission required to add in Manifest
URL metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
feed = service.getFeed(metafeedUrl, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
if (spreadsheets.size() > 0) {
spreadsheet = spreadsheets.get(i);//Get your Spreadsheet
}
} catch (Exception e) {
e.printStackTrace();
}
Thank you so so much Scorpion! It works!! I've been trying this for too long.
Ok here is my solution:
I started a new project and included these jars:
gdata-client-1.0
gdata-client-meta-1.0
gdata-core-1.0
gdata-spreadsheet-3.0
gdata-spreadsheet-meta-3.0
guava-13.0.1
and my code:
SpreadsheetService spreadsheet= new SpreadsheetService("v1");
spreadsheet.setProtocolVersion(SpreadsheetService.Versions.V3);
try {
spreadsheet.setUserCredentials("username", "password");
URL metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
SpreadsheetFeed feed = spreadsheet.getFeed(metafeedUrl, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
for (SpreadsheetEntry service : spreadsheets) {
System.out.println(service.getTitle().getPlainText());
}
} catch (AuthenticationException e) {
e.printStackTrace();
}
of course this is executed in a different thread not in the main thread. There is no java documentation for OAuth 2.0 but I will try and if I can't do it I'll ask here.
Again, thank you very much and I hope to help you when I work on this time enough. :)
(Feb 2017) The question (and most answers) are now out-of-date as:
GData APIs are the previous generation of Google APIs. While
not all GData APIs have been deprecated, all modern Google
APIs do not use the Google Data protocol
Google released a new Google Sheets API (v4; not GData) in
2016, and
Android Studio is now the preferred IDE over Eclipse. In order
to use Google APIs, you need to get the Google APIs Client Library
for Android (or for more general Java, the Google APIs Client
Library for Java). Now you're set.
To start, the latest Sheets API is much more powerful than all older versions. The latest API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (create frozen rows, perform cell formatting, resize rows/columns, add pivot tables, create charts, etc.).
That said, yeah, it's tough when there aren't enough good (working) examples floating around, right? In the official docs, we try to put "quickstart" examples in as many languages as possible to help get you going. In that spirit, here are the Android quickstart code sample as well as the more general Java Quickstart code sample. For convenience, here's the Sheets API JavaDocs reference.
Another answer suggested using OAuth2 for data authorization, which you can do with this auth snippet from the quickstart above, plus the right scope:
// Sheets RO scope
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS_READONLY};
:
// Initialize credentials and service object
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
If you're not "allergic" to Python, I've made several videos with more "real-world" examples using the Sheets API (non-mobile though):
Migrating SQL data to a Sheet (code deep dive post)
Formatting text using the Sheets API (code deep dive post)
Generating slides from spreadsheet data (code deep dive post)
Finally, note that the Sheets API performs document-oriented functionality as described above. For file-level access, i.e. import, export etc. you'd use the Google Drive API instead; specifically for mobile, use the Google Drive Android API. Hope this helps!
It's a complex process, but it can be done! I wrote a blog post on getting the basics up and running. And I've also published an open-source project that is actually useful, but still quite minimal. It uses OAuth, and therefore can pull the permission directly from Android's permission model (no hardcoded email/password!).
You need something to start the "Choose account intent":
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"},
false, null, null, null, null);
startActivityForResult(intent, 1);
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
And then when that intent returns, you can try to use the token that was returned (although note, if it's the first time the user may have to explicitly authorize your program; that's the UserRecoverableAuthException):
protected void onActivityResult(final int requestCode, final int resultCode,
final Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
final String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
System.err.println(accountName);
(new AsyncTask<String, String,String>(){
#Override
protected String doInBackground(String... arg0) {
try {
// Turn account name into a token, which must
// be done in a background task, as it contacts
// the network.
String token =
GoogleAuthUtil.getToken(
FullscreenActivity.this,
accountName,
"oauth2:https://spreadsheets.google.com/feeds https://docs.google.com/feeds");
System.err.println("Token: " + token);
// Now that we have the token, can we actually list
// the spreadsheets or anything...
SpreadsheetService s =
new SpreadsheetService("Megabudget");
s.setAuthSubToken(token);
// Define the URL to request. This should never change.
// (Magic URL good for all users.)
URL SPREADSHEET_FEED_URL = new URL(
"https://spreadsheets.google.com/feeds/spreadsheets/private/full");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed;
try {
feed = s.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
// Iterate through all of the spreadsheets returned
for (SpreadsheetEntry spreadsheet : spreadsheets) {
// Print the title of this spreadsheet to the screen
System.err.println(spreadsheet.getTitle().getPlainText());
}
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UserRecoverableAuthException e) {
// This is NECESSARY so the user can say, "yeah I want
// this app to have permission to read my spreadsheet."
Intent recoveryIntent = e.getIntent();
startActivityForResult(recoveryIntent, 2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}}).execute();
} else if (requestCode == 2 && resultCode == RESULT_OK) {
// After the user YAYs or NAYs our permission request, we are
// taken here, so if we wanted to grab the token now we could.
}
}
Here's my code for requesting the auth token...
AccountManager am = AccountManager.get(this);
Bundle options = new Bundle();
am.getAuthToken(
(am.getAccounts())[0], // My test device only has one account. I'll add a picker before releasing this app.
"oauth2:" + DriveScopes.DRIVE,
options,
true, // I've tried both true and false... doesn't seem to change anything?
new OnTokenAcquired(),
null); // I used to have a handler, but it absolutely never got called.
Here's the code that handles the token:
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey("xxxxxxxxxxxx.apps.googleusercontent.com"); // I replaced the number with x's. I'll explain where I got the number from below.
driveRequest.setOauthToken(token);
}
});
final Drive drive = b.build();
final com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle("My document");
body.setDescription("A test document");
body.setMimeType("text/plain");
java.io.File fileContent = new java.io.File("document.txt");
final FileContent mediaContent = new FileContent("text/plain", fileContent);
new Thread(new Runnable() {
public void run() {
com.google.api.services.drive.model.File file;
try {
file = drive.files().insert(body, mediaContent).execute();
Log.i("Hi", "File ID: " + file.getId());
} catch (IOException e) {
Log.i("Hi", "The upload/insert was caught, which suggests it wasn't successful...");
e.printStackTrace();
AccountManager am = AccountManager.get(activity);
am.invalidateAuthToken(am.getAccounts()[0].type, null);
Bundle options = new Bundle();
am.getAuthToken(
(am.getAccounts())[0],
"oauth2:" + DriveScopes.DRIVE,
options,
true,
new OnTokenAcquired(),
null);
}
}
}).start();
Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);
if (launch != null) {
Log.i("Hi", "Something came back as a KEY_INTENT");
startActivityForResult(launch, 3025);
return;
} else {
Log.i("Hi", "I checked, but there was nothing for KEY_INTENT.");
}
}
}
I have implemented onActivityResult and have it set up to log the requestCode and resultCode if it's ever invoked, but it never is. Were it to ever be invoked, it just fires off another token request if the requestCode is 3025 and the resultCode is RESULT_OK.
Here's how I got my clientID:
I went to Google APIs console or whatever it's called.
I made a new product.
I enabled and set up the Drive SDK (sort of... I'm not making a web app, so I just pointed the URL at a website I own.)
Under "API Access" I clicked "Create another client ID..." and set it up for an installed Android app. (The fingerprint may not be quite right? Would that cause the error?)
I copied the Client ID listed under Client ID for Installed Applications (not the one from Client ID for Drive SDK).
As it is, here's what I get from the log:
I checked, but there was nothing for KEY_INTENT // My log message.
The upload/insert was caught, which suggests it didn't work... // Another one of my log messages.
com.google.api.client.http.HttpResponseException: 400 Bad Request
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "keyInvalid",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request"
}
}
Followed by a more ordinary stack trace...
EDIT
Recently it stopped giving me 400 and instead started giving me 403 Forbidden, still with the domain of usageLimits, reason now being accessNotConfigured and message being Access Not Figured.
You are passing the Client ID you got from the APIs Console to driveRequest.setKey, however that method is used to set an API Key and not the Client ID. That's why your application is not correctly bound to the project from the APIs Console and your app is not allowed to use the API.
Once you get a valid OAuth token for the project identified by that Client ID, you set it by calling driveRequest.setOauthToken(String).
For more details about OAuth2 on Android check http://developer.android.com/training/id-auth/authenticate.html
The issue appears to have been that in APIs Console I hadn't turned on both DRIVE SDK and DRIVE API under services. They're separate, and one doesn't automatically turn the other on.