Search code examples
androidgoogle-analytics-apigoogle-signingoogle-api-clientandroid-googleapiclient

Using token of play-services-auth to authenticate with Google Analytics Data API in Android


I want to call Google Analytics Data API and Google Analytics Management API with Java client APIs. In the example they use a service account configured in a json file.

As I'm integrating other Google APIs as well, I use Google Play Services Auth for authentication (with OAuth 2), therefore I already have an access token, which I want to use. But I have no idea how to pass it to the Google Analytics client.

I've tried it that way:

GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(mContext);
String tokenString = GoogleAuthUtil.getToken(mContext, 
                                            account.getAccount(),
                                            "oauth2:https://www.googleapis.com/auth/analytics.readonly");
AccessToken token = new AccessToken(tokenString,
                                    // Set expiration time in one hour, 
                                    // as credentials are created every time
                                    // this method is called.
                                    new Date(System.currentTimeMillis() + 60 * 60 * 1000)));
Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(token).build();
ClientContext clientContext = ClientContext.newBuilder().setCredentials(credentials).build();
BetaAnalyticsDataClient client = BetaAnalyticsDataClient.create(BetaAnalyticsDataSettings.newBuilder(clientContext).build());

The problem is that the client context seems to have no default values and so I needed to feed it with all the information I don't know (and don't want to do it that way, as there are default values used, when I do not put my own client context. So I'd like to use the same default values as well). So this ends in an IllegalStateException (Missing required properties: defaultCallContext).

Is there a way to get a default client context and then just overwrite the credentials, or is there any other way to pass my own OAuth credentials?

The behavior is the same for Analytics Data and Management API by the way. So I guess the same solution will solve both problems.


Solution

  • Aorlinn,

    The BetaAnalyticsDataClient reference documentation contains the following snippet that shows how to override credentials:

     BetaAnalyticsDataSettings betaAnalyticsDataSettings =
         BetaAnalyticsDataSettings.newBuilder()
             .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
             .build();
     BetaAnalyticsDataClient betaAnalyticsDataClient =
         BetaAnalyticsDataClient.create(betaAnalyticsDataSettings);
    

    Please let me know if this helps.