Tag Archives: GoogleAPIClient

API Updates for Sign-In with Google

Posted by Laurence Moroney

With the release of Google Play services 8.3, we’ve made a lot of improvements to Sign-In with Google. In the first blog post of this ongoing series, we discussed the user interface improvements. Today, we will look further into the changes to the API to make building apps that Sign-In with Google easier than ever before.

Changes to basic sign in flow

When building apps that sign in with Google, you’ll notice that there are a lot of changes to make your code easier to understand and maintain.

Prior to this release, if you built an app that used Sign-In with Google, you would build one that attempted to connect to a GoogleApiClient. At this point the user was presented with an account picker and/or a permissions dialog, both of which would trigger a connection failure. You would have to handle these connection failures in order to sign in. Once the GoogleApiClient connected, then the user was considered to be signed in and the permissions could be granted. The process is documented in a CodeLab here.

Now, your code can be greatly simplified.

The process of signing in and connecting the GoogleApiClient are handled separately. Signing in is achieved with a GoogleSignInOptions object, on which you specify the parameters of the sign in, such as scopes that you desire. Here’s a code example:

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestEmail()
        .build();

Once you have a GoogleSignInOptions object, you can use it to configure the GoogleApiClient:

mGoogleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
        .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
        .build();

Here’s where your code will diverge greatly in the new API. Now, if you want to connect with a Google Account, instead of handling errors on the GoogleApiClient, you’ll instead use an intent that is initialized using the client.

Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);

Starting the intent will give you the account picker, and the scopes permission dialog if your GoogleSignInOptions requested anything other than basic scope. Once the user has finished interacting with the dialogs, an OnActivityResult callback will fire, and it will contain the requisite sign-in information.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleSignInResult(result);
    }
}

You can learn more about this code in the Integrating Google Sign-In quickstart, or by looking at the sample code.

Silent Sign-In

To further reduce friction for users in a multi-device world, the API supports silent sign in. In this case, if your user has given authorization to the app on a different device, the details will follow their account, and they don’t need to re-give them on future devices that they sign into, unless they deauthorize. An existing sign-in is also cached and available synchronously on the current device is available.

Using it is as simple as calling the silentSignIn method on the API.

OptionalPendingResult opr = 
Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);

Then, you can check the isDone() method on the pending result -- and if it returns true, the user is signed in, and you can get their status from the PendingResult. If it isn’t then you have to wait for a callback with the SignInResult

if (pendingResult.isDone()) {
     doStuffWith(pendingResult.get());
 } else {
     // There's no immediate result ready, displays some progress indicator and waits for the
     // async callback.
     showProgressIndicator();
     pendingResult.setResultCallback(new ResultCallback() {
         @Override
         public void onResult(@NonNull GoogleSignInResult result) {
             updateButtonsAndStatusFromSignInResult(result);
             hideProgressIndicator();
         }
     });
 }

Customizing the Sign-In Button

When building apps that Sign-In with Google, we provide a SignInButton object that has the Google branding, and which looks like this:


You can customize this button with a number of properties and constants that are documented in the API here.

The branding guidelines are available here, and they include versions of the buttons in PNG, SVG, EPS and other formats in many resolutions, including all the different states of the button. These files may be used for localization of the button, and if you need to match the style of the button to your app, guidelines are provided.

This only deals with the Android side of your app. You’ll likely have a server back end, and you may want to use the credentials on that securely.

In the next blog post, we’ll discuss how to use Sign-In with Google in server-side scenarios, including how to securely pass your credentials to your own server, and how to use Google back-end services, such as Google Drive, with the permission and credentials from users.

Google Play services 7.0 – Places Everyone!

Posted by Ian Lake, Developer Advocate

Today, we’re bringing you new tools to build better apps with the rollout of Google Play services 7.0. With this release, we’re delivering improvements to location settings experiences, a brand new API for place information, new fitness data, automatic integration of AdMob and Google Analytics, Google Play Games, and more.

Location Settings Dialog

While the FusedLocationProviderApi combines multiple sensors to give you the optimal location, the accuracy of the location your app receives still depends greatly on what settings are enabled on the device (e.g. GPS, wifi, airplane mode, etc). In Google Play services 7.0, we’re introducing a standard mechanism to check that the necessary location settings are enabled for a given LocationRequest to succeed. If there are possible improvements, you can display a one touch control for the user to change their settings without leaving your app.

This API provides a great opportunity to make for a much better user experience, particularly if location information is critical to the user experience of your app such as was the case with Google Maps when they integrated the Location Settings dialog and saw a dramatic increase in the number of users in a good location state.

Places API

Location can be so much more than a latitude and longitude: the new Places API makes it easy to get details from Google’s database of places and businesses. The built-in place picker makes it easy for the user to pick their current place and provides all the relevant place details including name, address, phone number, website, and more.

If you prefer to provide your own UI, the getCurrentPlace() API returns places directly around the user’s current location. Autocomplete predictions are also provided to allow a low latency search experience directly within your app.

You can also manually add places with the addPlace() API and report that the user is at a particular place, ensuring that even the most explorative users can input and share their favorite new places.

The Places API will also be available cross-platform: in a few days, you’ll be able to apply for the Places API for iOS beta program to ensure a great and consistent user experience across mobile platforms.

Google Fit

Google Fit makes building fitness apps easier with fitness specific APIs on retrieving sensor data like current location and speed, collecting and storing activity data in Google Fit’s open platform, and automatically aggregating that data into a single view of the user’s fitness data.

In Google Play services 7.0, the previous Fitness.API that you passed into your GoogleApiClient has now been replaced with a number of APIs, matching the high level set of Google Fit Android APIs:

  • SENSORS_API to access raw sensor data via SensorsApi
  • RECORDING_API to record data via RecordingApi
  • HISTORY_API for inserting, deleting, or reading data via HistoryApi
  • SESSIONS_API for managing sessions via SessionsApi
  • BLE_API to interact with Bluetooth Low Energy devices via BleApi
  • CONFIG_API to access custom data types and settings for Google Fit via ConfigApi

This change significantly reduces the memory requirement for Google Fit enabled apps running in the background. Like always, apps built on previous versions of Google Play services will continue to work, but we strongly suggest you rebuild your Google Fit enabled apps to take advantage of this change.

Having all the data can be an empowering part of making meaningful changes and Google Fit is augmenting their existing data types with the addition of body fat percentage and sleep data.

Google Mobile Ads

We’ve found integration of AdMob and Google Analytics a powerful combination for analyzing how your users really use your app since we launched Google Analytics in AdMob last year. This new release enables any Google Mobile Ads SDK implementation to automatically get Google Analytics integration giving you the number of users and sessions, session duration, operating systems, device models, geography, and automatic screen reporting without any additional development work.

In addition, we’ve made numerous improvements across the SDK including ad request prefetching (saving battery usage and improving apparent latency) and making the SDK MRAIDv2 compliant.

Google Play Games

Announced at Game Developers Conference (GDC), we’re offering new tools to supercharge your games on Google Play. Included in Google Play services 7.0 is the Nearby Connections API, allowing games to seamlessly connect smartphones and tablets as second-screen controls to the game running on your TV.

App Indexing

App Indexing lets Google index apps just like websites, enabling Google search results to deep-link directly into your native app. We've simplified the App Indexing API to make this integration even easier for you by combining the existing view()/viewEnd() and action()/end() flows into a single start() and end() API.

Changes to GoogleApiClient

GoogleApiClient serves as the common entry point for accessing Google APIs. For this release, we’ve made retrieval of Google OAuth 2.0 tokens part of GoogleApiClient, making it much easier to request server auth codes to access Google APIs.

SDK Coming Soon!

We will be rolling out Google Play services 7.0 over the next few days. Expect an update to this blog post, published documentation, and the availability of the SDK once the rollout is completed.

To learn more about Google Play services and the APIs available to you through it, visit the Google Services section on the Android Developer site.