How to Get OAuth Token From GoogleApiClient

2019-09-03 08:31发布

问题:

I am trying to build an Android application that created a spreadsheet in Google Drive and then adds some data to it. I can successfuly create the spreadsheet using the Google Drive Android API which involves creating a GoogleApiClient and using a class that implements GoogleApiClient.ConnectionCallbacks.

When I start the application I make a new GoogleApiClient and am prompted to select an account. In the onConnected callback I can new pass my GoogleApiClient to Drive.DriveApi to query and create files and folders.

However, to add data to a Google sheet I need to use the GoogleSheets API. This does not have an Android API as far as I can tell but it does have a gdata API. In order to use it however I need an OAuth token.

Is there anyway I can get an OAuth token from the GoogleApiClient object?

回答1:

Yes you can just use

    GoogleAccountCredential mCredential;
String[] SCOPES = {"https://www.googleapis.com/auth/userinfo.profile"};

     mCredential = GoogleAccountCredential.usingOAuth2(mContext, Arrays.asList(SCOPES))
                    .setBackOff(new ExponentialBackOff())
                    .setSelectedAccountName(ACC_NAME);

        GoogleAuthUtil.getToken(mContext, mCredential.getSelectedAccountName(),SCOPE)

GoogleAuthUtil.getToken



回答2:

You can use GoogleAuthUtil.getToken()

call this method in an AsyncTask as it performs a network operation.