Hello Friends, Today I am going to share a code to login with Google in Android. Today Almost all mobile and web apps allow us to login with google. Login with google feature in any app is very convenient feature, because of this feature we don’t have to create and remember new password for each app we use. Here we are going to create a sample google login app to demonstrate how to integrate google login and fetch user’s profile.
Prerequisites
- A compatible Android device that runs Android 4.1 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 15.0.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 4.1 (Jelly Bean) 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.
This prerequisites is taken from google’s official documentation on integration of google sign in to your android app.
Integration
To integrate google login in our app we are going to follow step by step procedure as follows:-
Step 1: Add Google Play Services
Updating project’s top-level build.gradle so that it will look like something below. We basically need to include google() or maven url ‘https://maven.google.com‘ in case of your gradle version is lower than 4.1
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 |
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() // If you're using a version of Gradle lower than 4.1, you must instead use: // maven { // url 'https://maven.google.com' // } } dependencies { classpath 'com.android.tools.build:gradle:3.4.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } |
Updating app-level build.gradle so that it will look like something below. We basically need to add play-services-auth dependency as mentioned below. please note that compile is old way to define dependency but the new way is implementation that’s why we will see implementation instead of compile in below build.gradle file.
compile ‘com.google.android.gms:play-services-auth:16.0.1’
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 |
apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.zatackcoder.googlelogin" minSdkVersion 16 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.google.android.gms:play-services-auth:16.0.1' } |
Step 2: Configure a Google API Console project
To configure Google API Console project we have to visit https://console.developers.google.com and have to login to our google account if not already logged in.
Now we have to create a project if not already created or we can select existing project if already created.
Then we’ll go to Credentials option and click on create credentials and select OAuth client ID option from the drop down list
Now we have to select Android Option in application type and then we need to fill all the fields i.e Name, SHA-1 fingerprint and Package name. In the name field we can type anything we want i.e OAuth Client, GoogleLogin etc., In the package name we need to enter package name of our app which we can find in AndroidManifest.xml, here we can see that package name is com.zatackcoder.googlelogin and finally SHA-1 fingerprint.
To get SHA-1 use keytool utility for which open terminal and type below command and then it will ask for password then enter android, because the default password for the debug keystore is android. And then we will see Certificate fingerprints as above screenshot.
Now we’ll copy SHA1 from terminal and paste it in Signing-certificate fingerprint field and then click on create.
After clicking on create we’ll see a entry in OAuth 2.0 client IDs list as shown above.
Step 3: Add Sign In Button in App and Configuring
LoginActivity.java
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 |
package com.zatackcoder.googlelogin; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; 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.SignInButton; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.tasks.Task; public class LoginActvity extends AppCompatActivity implements View.OnClickListener { static int RC_SIGN_IN = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_actvity); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); MainActivity.mGoogleSignInClient = GoogleSignIn.getClient(this, gso); SignInButton signInButton = findViewById(R.id.sign_in_button); signInButton.setSize(SignInButton.SIZE_STANDARD); signInButton.setOnClickListener(this); } @Override protected void onStart() { super.onStart(); /*Directly start MainActivity if Already LoggedIn*/ GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this); if(account != null) { MainActivity.account = account; startActivity(new Intent(this, MainActivity.class)); finish(); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sign_in_button: signIn(); break; } } public void signIn() { Intent signInIntent = MainActivity.mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { // The Task returned from this call is always completed, no need to attach // a listener. Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); handleSignInResult(task); } } private void handleSignInResult(Task<GoogleSignInAccount> completedTask) { try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); // Signed in successfully, show authenticated UI. if(account != null) { MainActivity.account = account; startActivity(new Intent(this, MainActivity.class)); finish(); } } catch (ApiException e) { // The ApiException status code indicates the detailed failure reason. // Please refer to the GoogleSignInStatusCodes class reference for more information. Log.w("LoginActivity", "signInResult:failed code=" + e.getStatusCode()); } } } |
activity_login_actvity.xml
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"?> <android.support.constraint.ConstraintLayout 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=".LoginActvity"> <com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> |
Screenshot
MainActivity.java
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 |
package com.zatackcoder.googlelogin; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; 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.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import java.io.InputStream; public class MainActivity extends AppCompatActivity implements View.OnClickListener { static GoogleSignInClient mGoogleSignInClient; static GoogleSignInAccount account; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(account == null) { startActivity(new Intent(this, LoginActvity.class)); } else { TextView name = findViewById(R.id.name); name.setText(account.getDisplayName()); /*Loading and Showing Profile Photo*/ new LoadAndShowPhoto((ImageView) findViewById(R.id.photo)).execute(account.getPhotoUrl().toString()); findViewById(R.id.sign_out).setOnClickListener(this); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sign_out : signOut(); break; } } private void signOut() { if(mGoogleSignInClient != null) { mGoogleSignInClient.signOut().addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { startActivity(new Intent(MainActivity.this, LoginActvity.class)); finish(); } }); } } private class LoadAndShowPhoto extends AsyncTask<String, Void, Bitmap> { ImageView imageView; public LoadAndShowPhoto(ImageView imageView) { this.imageView = imageView; Toast.makeText(getApplicationContext(), "Loading Photo..", Toast.LENGTH_SHORT).show(); } protected Bitmap doInBackground(String... urls) { String imageURL = urls[0]; Bitmap bimage = null; try { InputStream in = new java.net.URL(imageURL).openStream(); bimage = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("LoadAndShowPhoto", e.getMessage()); } return bimage; } protected void onPostExecute(Bitmap result) { imageView.setImageBitmap(result); } } } |
activity_main.xml
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 |
<?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:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="vertical"> <android.support.v7.widget.AppCompatImageView android:id="@+id/photo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" app:srcCompat="@mipmap/ic_launcher_round" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="8dp" android:text="Hello World!" /> <Button android:id="@+id/sign_out" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Sign Out" android:layout_gravity="center"/> </LinearLayout> </LinearLayout> |
Screenshot
Download Android Studio Project
Login with Google in Android
Thanks for stopping by
Please do share if you like it
Comments