Start Integrating Google Sign-In into Your Android App start logging in Google for your application, you must configure the Google API Console project and create your Android Studio project.
Visit Google Api Console to Configure and get configuration file to add to your android project
1. Add the dependency to your project-level build.gradle:
Add the SignInButton in your application's layout:
Get a configuration file
The configuration file provides service specific information for your application. To achieve this, you need to select an existing project for your application or create a new one. You should also provide a name for your application package.Visit Google Api Console to Configure and get configuration file to add to your android project
- Add your android project package.
- Authenticating Your Client
Open a terminal and run the keytool utility provided with Java to get the SHA-1 fingerprint of the certificate. You should get both the release and debug certificate fingerprints. Visit my previous post How To Get SHA1 Key
- Click continue to generate configuration file to add to android project
- Click download configuration file and then copy google-service.json
to app folder in your android project.
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:1. Add the dependency to your project-level build.gradle:
classpath 'com.google.gms:google-services:3.0.0'
2. Add the plugin to your app-level build.gradle:apply plugin: 'com.google.gms.google-services'
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" />
In the Android activity (for example, in the onCreate method), register your button's OnClickListener to sign in the user when clicked:// Set the dimensions of the sign-in button.
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_STANDARD);
findViewById(R.id.sign_in_button).setOnClickListener(this);
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 @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);
}
In the activity's onActivityResult method, retrieve the sign-in result with @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);
}
}
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();
Then, also in your main 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();
Here's full source code
Dependency in app level build.gradledependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:cardview-v7:25.2.0'
compile 'com.google.android.gms:play-services-auth:10.2.1'
compile 'com.squareup.picasso:picasso:2.3.2'
testCompile 'junit:junit:4.12'
}
activity_main.xml<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="wolaris.google.signin.MainActivity"
android:orientation="vertical"
android:background="@color/colorPrimary">
<ImageView
android:layout_width="55dp"
android:layout_height="55dp"
android:src="@mipmap/ic_launcher"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="8dp"
android:layout_marginTop="?actionBarSize"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/app_name"
android:textSize="20sp"
android:layout_marginBottom="@dimen/activity_horizontal_margin"
android:textColor="@color/cardview_light_background"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<com.google.android.gms.common.SignInButton
android:id="@+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="gone"/>
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="visible" />
<LinearLayout android:id="@+id/signInView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
android:visibility="gone" >
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/activity_horizontal_margin">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:orientation="horizontal">
<ImageView android:id="@+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@mipmap/ic_launcher"
android:layout_gravity="center_horizontal"
android:layout_marginRight="@dimen/activity_horizontal_margin"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView android:id="@+id/statusView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_marginBottom="8dp"
android:textColor="@color/cardview_dark_background"
android:textSize="16sp"
android:textStyle="bold"/>
<TextView android:id="@+id/emailView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="wolaris@example.com"
android:textColor="@color/cardview_dark_background"
android:textSize="14sp"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
<Button
android:id="@+id/sign_out_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#40000000"
android:textColor="@color/cardview_light_background"
android:text="SIGN OUT"
android:onClick="onClick"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
MainActivity.javapackage wolaris.google.signin;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.squareup.picasso.Picasso;
public class MainActivity extends FragmentActivity
implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private final static int RC_SIGN_IN = 100;
private TextView mStatusTextView;
private View mSignInView;
private View mProgressView;
private SignInButton signInButton;
private ImageView mImageView;
private TextView mEmailTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Set the dimensions of the sign-in button.
signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setOnClickListener(this);
mStatusTextView = (TextView)findViewById(R.id.statusView);
mEmailTextView = (TextView)findViewById(R.id.emailView);
mImageView = (ImageView)findViewById(R.id.imageView);
mSignInView = findViewById(R.id.signInView);
mProgressView = findViewById(R.id.progressBar);
}
@Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(GoogleSignInResult googleSignInResult) {
handleSignInResult(googleSignInResult);
}
});
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed:" + connectionResult);
showProgress(false);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
showProgress(true);
signIn();
break;
case R.id.sign_out_button:
signOut();
break;
}
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
updateUI(false);
}
});
}
@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);
}
}
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(acct.getDisplayName());
mEmailTextView.setText(acct.getEmail());
Picasso.with(this).load(acct.getPhotoUrl()).into(mImageView);
updateUI(true);
showProgress(false);
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
showProgress(false);
}
}
private void updateUI(boolean signedIn){
mSignInView.setVisibility(signedIn ? View.VISIBLE : View.GONE);
signInButton.setVisibility(signedIn ? View.GONE : View.VISIBLE);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
}
AndroidManifest.xml<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="wolaris.google.signin">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:hardwareAccelerated="true"
android:largeHeap="true">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>