Google Integration with Android Application

November 15, 2017
admin

Google sign-in lets users sign in to your Android app with their existing Google account and get their profile information like name, email, profile pic and other details. By integrating google plus login in your apps, you can get all the user details in one shot.

Prerequisites

This guide is written for users of Android Studio, which is the recommended development environment.

  • Android 2.3 or newer and includes the Google Play Store or an emulator with an AVD that runs the Google APIs platform based on Android 4.2.2 or newer and has Google Play Services version 9.8.0 or newer.
  • The latest version of the Android SDK, including the SDK Tools component. The SDK is available from the Android SDK Manager in Android Studio.
  • A project configured to compile against Android 2.3 (Gingerbread) or newer.
  • The Google Play Services SDK:
    • In Android Studio, select Tools > Android > SDK Manager.
    • Scroll to the bottom of the package list and select Extras > Google Repository. The package is downloaded to your computer and installed in your SDK environment at android-sdk-folder/extras/google/google_play_services.
Get a configuration file

The configuration file provides service-specific information for your app. To get it, you must select an existing project for your app or create a new one. You’ll also need to provide a package name for your app.
When you generate the configuration file, you will also need to provide the SHA-1 hash of your signing certificate. See Authenticating Your Client for information.

Add the configuration file to your project

Copy the google-services.json file you just downloaded into the app/ or mobile/ directory of your Android Studio project. Open the Android Studio Terminal pane:

Add the Google Services plugin

The Google Services plugin for Gradle parses configuration information from the google-services.json file. Add the plugin to your project by updating your top-level build.gradle and your app-level build.gradle files as follows:
Add the dependency to your project-level build.gradle:
classpath ‘com.google.gms:google-services:3.0.0’
Add the plugin to your app-level build.gradle:
apply plugin: ‘com.google.gms.google-services’

Add Google Play Services

In your app-level build.gradle file, declare Google Play Services as a dependency:
apply plugin: ‘com.android.application’

dependencies {

compile 'com.google.android.gms:play-services-auth:9.8.0'

}
Get your backend server’s OAuth 2.0 client ID

If your app authenticates with a backend server or accesses Google APIs from your backend server, you must get the OAuth 2.0 client ID that was created for your server. To find the OAuth 2.0 client ID:
1. Open the Credentials page in the API Console.
2. The Web application type client ID is your backend server’s OAuth 2.0 client ID.
Note: If you haven’t recently created a new Android client, you might not have a Web application type client ID. You can create one by opening the Credentials page and clicking New credentials > OAuth client ID.
Pass this client ID to the requestIdToken or requestServerAuthCode method when you create the GoogleSignInOptions object.

Configure Google Sign-In and the GoogleApiClient object

1. In your sign-in activity’s onCreate method, configure Google Sign-In to request the user data required by your app. For example, to configure Google Sign-In to request users’ ID and basic profile information, create a GoogleSignInOptions object with the DEFAULT_SIGN_IN parameter. To request users’ email addresses as well, create the GoogleSignInOptions object with the requestEmail option.
// Configure sign-in to request the user’s ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.

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

SignInActivity.java

If you need to request additional scopes to access Google APIs, specify them with requestScopes.

2. Then, also in your sign-in activity’s onCreate method, create a GoogleApiClient object with access to the Google Sign-In API and the options you specified.

// Build a GoogleApiClient with access to the Google Sign-In API and the
// options specified by gso.

mGoogleApiClient = new GoogleApiClient.Builder(this)
 .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
 .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
 .build();
Add the Google Sign-In button to your app

1. Add the SignInButton in your application’s layout:

<com.google.android.gms.common.SignInButton

android:id="@+id/sign_in_button"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

2. Optional: If you are using the default sign-in button graphic instead of providing your own sign-in button assets, you can customize the button’s size with the setSize method.
// Set the dimensions of the sign-in button.

SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);

signInButton.setSize(SignInButton.SIZE_STANDARD);

SignInActivity.java

3. In the Android activity (for example, in the onCreate method), register your button’s OnClickListener to sign in the user when clicked:3.  In the Android activity (for example, in the onCreate method), register your button’s OnClickListener to sign in the user when clicked:findViewById(R.id.sign_in_button).setOnClickListener(this);

Start the sign-in flow

1. In the activity’s onClick method, handle sign-in button taps by creating a sign-in intent with the getSignInIntent method, and starting the intent with startActivityForResult.

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.sign_in_button:
            signIn();
            break;
        // ...
    }
}private void signIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

Starting the intent prompts the user to select a Google account to sign in with. If you requested scopes beyond profile, email, and openid, the user is also prompted to grant access to the requested resources.

2. In the activity’s onActivityResult method, retrieve the sign-in result with getSignInResultFromIntent.

@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);

    }

}

After you retrieve the sign-in result, you can check if sign-in succeeded with the isSuccess method. If sign-in succeeded, you can call the getSignInAccount method to get a GoogleSignInAccount object that contains information about the signed-in user, such as the user’s name.

private void handleSignInResult(GoogleSignInResult result) {
 Log.d(TAG, "handleSignInResult:" + result.isSuccess());
 if (result.isSuccess()) {
 // Signed in successfully, show authenticated UI.
 GoogleSignInAccount acct = result.getSignInAccount();
 mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName()));
 updateUI(true);
 } else {
 // Signed out, show unauthenticated UI.
 updateUI(false);
 }
}

You can also get the user’s email address with getEmail, the user’s Google ID (for client-side use) with getId, and an ID token for the user with getIdToken. If you need to pass the currently signed-in user to a backend server, send the ID token to your backend server and validate the token on the server.

Contributor: Ashiqur RahmanNascenia

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.