Here is the Google Login Android Tutorial. If you are looking to integrating Google Login in your android application, then it is the right place.
Puting a Google Login in your Android Application is a perfect idea, as people hate filling forms, and remembering passwords. So if a Google Login is there on your android application, then it becomes convenient for your users to SignUp and SignIn in your app.
Here to integrate Google Login, I am going to use Firebase. Like the old way of adding Google Login in the app is obsolete and now google recommends using Firebase.
So let’s learn how to Integrate Google Login in Android.
Table of Contents
Google Login Android using Firebase Video Tutorial
- You can watch this detailed video as well. Here I am covering the Google Login using Firebase step by step.
Google Login Android using Firebase
As always we will start a new Android Studio Project.
Creating an Android Project
- Open Android Studio (Here I am using Android Studio 3.0). And you need to create a project with an Empty Activity. I created a project named GoogleLoginExample.
- Once your project is loaded then click on Tools->firebaseÂ
- Then you will see a new window on the right. Here you need to select Authentication.
- Now you need to connect to firebase. It will again open a window, and from this window, you can create a new Firebase Project, or if you want you can also choose an existing one.
- After connecting to Firebase, click on Add Authentication and accept the changes. It will add all the required dependencies.
Enabling Google Login in Firebase Console
- If we want to use Google Login with Firebase, then we also need to enable it in the Firebase Console (Default disables it).
- To enable it, go to Firebase Console (console.firebase.google.com). Then from the right, select Authentication, then select SIGN-IN METHOD, and here you need to allow Google Option. (See the image below it is disabled, and you need to enable it).
Adding Dependencies
- We added the Firebase Dependencies in above step, but we need to add one more. To do this open your app level build.gradle file and add the line as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.0.2' //this is added when we integrated firebase implementation 'com.google.firebase:firebase-auth:11.6.0' //this line you need to add //make sure you are using the same version for both //and also make sure you are using version atleast 11.6.0 compile 'com.google.android.gms:play-services-auth:11.6.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' } |
- Be sure you are using the same versions of firebase-auth, and play-services-auth.
- Though you can use any button, we have an inbuilt Google Sign-In button. So here I will be using the default Google Sign-In button that is inbuilt.
- Come inside activity_main.xml and write the following code to add the Google Sign-In Button.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="net.simplifiedcoding.googleloginexample.MainActivity"> <com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> </RelativeLayout> |
- You will see the following layout after writing the above code in your activity_main.xml.
Creating a Profile Activity
- On successful login, we will take the user to a Profile Screen. Create a new Empty Activity named ProfileActivity.
- On the layout file activity_profile.xml write the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="net.simplifiedcoding.googleloginexample.ProfileActivity"> <ImageView android:id="@+id/imageView" android:layout_width="100dp" android:layout_height="100dp" /> <TextView android:id="@+id/textViewName" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <TextView android:id="@+id/textViewEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> </LinearLayout> |
Performing Google Sign-In
- Here comes the most important thing. Come on MainActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
package net.simplifiedcoding.googleloginexample; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; public class MainActivity extends AppCompatActivity { //a constant for detecting the login intent result private static final int RC_SIGN_IN = 234; //Tag for the logs optional private static final String TAG = "simplifiedcoding"; //creating a GoogleSignInClient object GoogleSignInClient mGoogleSignInClient; //And also a Firebase Auth object FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //first we intialized the FirebaseAuth object mAuth = FirebaseAuth.getInstance(); //Then we need a GoogleSignInOptions object //And we need to build it as below GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); //Then we will get the GoogleSignInClient object from GoogleSignIn class mGoogleSignInClient = GoogleSignIn.getClient(this, gso); //Now we will attach a click listener to the sign_in_button //and inside onClick() method we are calling the signIn() method that will open //google sign in intent findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signIn(); } }); } @Override protected void onStart() { super.onStart(); //if the user is already signed in //we will close this activity //and take the user to profile activity if (mAuth.getCurrentUser() != null) { finish(); startActivity(new Intent(this, ProfileActivity.class)); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //if the requestCode is the Google Sign In code that we defined at starting if (requestCode == RC_SIGN_IN) { //Getting the GoogleSignIn Task Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { //Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); //authenticating with firebase firebaseAuthWithGoogle(account); } catch (ApiException e) { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); //getting the auth credential AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); //Now using firebase we are signing in the user here mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); Toast.makeText(MainActivity.this, "User Signed In", Toast.LENGTH_SHORT).show(); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.getException()); Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } // ... } }); } //this method is called on click private void signIn() { //getting the google signin intent Intent signInIntent = mGoogleSignInClient.getSignInIntent(); //starting the activity for result startActivityForResult(signInIntent, RC_SIGN_IN); } } |
- Now you can try running your application. You should be navigated to the Profile Activity (Check the Video).
Getting Some Basic Info from Google
- On successful login, you can get the user’s display name, profile picture, and email. For the profile image, you will get the URL to the image. So to display the image we again need a library called Glide, and it will help us in loading image from a URL.
Adding Glide
- Again add the following line inside you app level build.gradle.
1 2 3 4 |
compile 'com.github.bumptech.glide:glide:4.3.1' annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1' |
- Now on the project level build.gradlle add the following.
1 2 3 4 5 6 7 8 9 10 11 12 |
allprojects { repositories { google() jcenter() //add these two lines mavenCentral() maven { url 'https://maven.google.com' } } } |
- Now sync your project and you are done.
Displaying User Information
- Now, come inside ProfileActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
package net.simplifiedcoding.googleloginexample; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class ProfileActivity extends AppCompatActivity { ImageView imageView; TextView textName, textEmail; FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); mAuth = FirebaseAuth.getInstance(); imageView = findViewById(R.id.imageView); textName = findViewById(R.id.textViewName); textEmail = findViewById(R.id.textViewEmail); FirebaseUser user = mAuth.getCurrentUser(); Glide.with(this) .load(user.getPhotoUrl()) .into(imageView); textName.setText(user.getDisplayName()); textEmail.setText(user.getEmail()); } @Override protected void onStart() { super.onStart(); //if the user is not logged in //opening the login activity if (mAuth.getCurrentUser() == null) { finish(); startActivity(new Intent(this, MainActivity.class)); } } } |
- Now, you can try running the application.
Bingo! It is working fine.
Google Login Android Tutorial Source Code Download
- If you are having any troubles, then I have my source code for you as well. Unlock the below link to download source code.
[sociallocker id=1372] Google Login Android Tutorial Source Code Download [/sociallocker]
So that’s it for this Google Login Android Tutorial friends. Let me know in the comment section if you have any confusions.
Also if you found this Google Login Android Tutorial helpful, then please SHARE it with your friends. Thank You 🙂