Rapid Subscribe Android App

Rapid Subscribe Android App
Rapid Subscriber

Recent Posts

Integrating Google Sign-In in Android app

In this, We will integrate Google Sign-In in our Android Application using Google API. Combining Google API in the Android App helps people to log in using Google Account.


First, create a new project in Android studio and finish your Gradle build.


Then, add a library dependency in your app-level Gradle file.

 implementation 'com.google.android.gms:play-services-auth:17.0.0'  
 implementation 'com.github.bumptech.glide:glide:4.8.0' // to get image of a google account  

Then link your app on Google developer account from here.


In Configure a project, 



configure a project on Google Developers for Google Sign-in to your Android Application
Configure a Project


Select create a new project and name your project.



Configure a project on Google Developers for Google Sign-In to your Android Application
Name your Project


Then your product name and next then select Android from the Drop-down menu.

product name for Google Sign-in project Configuration
Product name


Select Android during configuring project for Google Sign-in
Select Android


Then write your package name. 



Package name of Project during Google Sign-in Configuration
Package name

For SHA-1 open Android Studio. Click on View-> Tools and Windows -> Gradle

Open Gradle and Find SHA-1 Key in Android Studio
Open Gradle

From there, open app -> Tasks -> Android -> SigningReport

Your Sha-1 key is shown in your run section from below.



Open Signing report for SHA-1 Key from gradle section and SHA-1 key is open in run section below
Signing Report and SHA-1 Key


paste that Sha-1 key during configure project in your Sign-in and click create.


SHA-1 Key for Adding Google Sign-in Project to your Android Application
Paste your SHA-1 and Create


Then Add sign-in button in your activitymain.xml


activitymain.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <androidx.constraintlayout.widget.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=".MainActivity">  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Hello World!"  
     app:layout_constraintBottom_toBottomOf="parent"  
     app:layout_constraintLeft_toLeftOf="parent"  
     app:layout_constraintRight_toRightOf="parent"  
     app:layout_constraintTop_toTopOf="parent" />  
   <com.google.android.gms.common.SignInButton  
     android:id="@+id/sign_in_button"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content" />  
 </androidx.constraintlayout.widget.ConstraintLayout>  

Then add some variables in your MainActivity.java

MainActivity.java

 public class MainActivity extends AppCompatActivity {  
   GoogleSignInClient mGoogleSignInClient;  
   private int RC_SIGN_IN = 1;  
   SignInButton signInButton;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);    

Remaining code of MainActivity.java


MainActivity.java

 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);  
     signInButton = findViewById(R.id.sign_in_button);  
     signInButton.setSize(SignInButton.SIZE_STANDARD);  
     signInButton.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View view) {  
         signIn();  
       }  
     });  
     GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  
         .requestEmail()  
         .build();  
     mGoogleSignInClient = GoogleSignIn.getClient(this, gso);  
     GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);   
   }  
   private void signIn() {  
     Intent signInIntent = 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);  
       if(completedTask.isSuccessful())  
       {  
         startActivity(new Intent(MainActivity.this,ProfileActivity.class));  
       }  
       else  
       {  
         Toast.makeText(this, "Error in Signing ", Toast.LENGTH_SHORT).show();  
       }  
     } catch (ApiException e) {  
       // The ApiException status code indicates the detailed failure reason.  
       // Please refer to the GoogleSignInStatusCodes class reference for more information.  
       Log.w("TAG", "signInResult:failed code=" + e.getStatusCode());  
       // updateUI(null);  
     }  
   }  
 }  


Here, we get all values and token from google account. and here we specify that if our sign-in will be successful then we goto our next profile activity where we show our user information.



activityprofile.xml

 <?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=".ProfileActivity">  
   <LinearLayout  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:gravity="center"  
     android:orientation="vertical">  
     <ImageView  
       android:layout_width="80dp"  
       android:layout_height="80dp"  
       android:id="@+id/profileImage"  
       />  
     <TextView  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:id="@+id/name"  
       android:text="name"  
       android:textSize="20dp"  
       android:layout_marginTop="20dp"/>  
     <TextView  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:id="@+id/email"  
       android:textSize="20dp"  
       android:text="email"  
       android:layout_marginTop="20dp"/>  
     <TextView  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:id="@+id/userId"  
       android:textSize="20dp"  
       android:text="id"  
       android:layout_marginTop="20dp"/>  
     <Button  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:id="@+id/logoutBtn"  
       android:text="Logout"  
       android:layout_marginTop="30dp"/>  
   </LinearLayout>  
 </RelativeLayout>  

Here, we create an Image view, three Text views and a log out button.


Profileactivity.Java

 package studio.harpreet.googlesignin;  
 import android.content.Intent;  
 import android.graphics.Bitmap;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.ImageView;  
 import android.widget.TextView;  
 import android.widget.Toast;  
 import androidx.annotation.NonNull;  
 import androidx.appcompat.app.AppCompatActivity;  
 import com.bumptech.glide.Glide;  
 import com.bumptech.glide.request.animation.GlideAnimation;  
 import com.bumptech.glide.request.target.SimpleTarget;  
 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.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;  
 public class ProfileActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {  
   Button logoutBtn;  
   TextView userName,userEmail,userId;  
   ImageView profileImage;  
   private GoogleApiClient googleApiClient;  
   private GoogleSignInOptions gso;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_profile);  
     logoutBtn=(Button)findViewById(R.id.logoutBtn);  
     userName=(TextView)findViewById(R.id.name);  
     userEmail=(TextView)findViewById(R.id.email);  
     userId=(TextView)findViewById(R.id.userId);  
     profileImage=(ImageView)findViewById(R.id.profileImage);  
     gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  
         .requestEmail()  
         .build();  
     googleApiClient=new GoogleApiClient.Builder(this)  
         .enableAutoManage(this,this)  
         .addApi(Auth.GOOGLE_SIGN_IN_API,gso)  
         .build();  
     logoutBtn.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View view) {  
         Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(  
             new ResultCallback<Status>() {  
               @Override  
               public void onResult(Status status) {  
                 if (status.isSuccess()){  
                   gotoMainActivity();  
                 }else{  
                   Toast.makeText(getApplicationContext(),"Session not close",Toast.LENGTH_LONG).show();  
                 }  
               }  
             });  
       }  
     });  
   }  
   @Override  
   protected void onStart() {  
     super.onStart();  
     OptionalPendingResult<GoogleSignInResult> opr= Auth.GoogleSignInApi.silentSignIn(googleApiClient);  
     if(opr.isDone()){  
       GoogleSignInResult result=opr.get();  
       handleSignInResult(result);  
     }else{  
       opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {  
         @Override  
         public void onResult(@NonNull GoogleSignInResult googleSignInResult) {  
           handleSignInResult(googleSignInResult);  
         }  
       });  
     }  
   }  
   private void handleSignInResult(GoogleSignInResult result){  
     if(result.isSuccess()){  
       GoogleSignInAccount account=result.getSignInAccount();  
       userName.setText(account.getDisplayName());  
       userEmail.setText(account.getEmail());  
       userId.setText(account.getId());  
       try{  
         Glide.with(this).load(account.getPhotoUrl()).into(profileImage);  
         Toast.makeText(this, "Image View", Toast.LENGTH_SHORT).show();  
       }catch (NullPointerException e){  
         Toast.makeText(getApplicationContext(),"image not found",Toast.LENGTH_LONG).show();  
       }  
     }else{  
       gotoMainActivity();  
     }  
   }  
   private void gotoMainActivity(){  
     Intent intent=new Intent(this,MainActivity.class);  
     startActivity(intent);  
   }  
   @Override  
   public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {  
   }  
 }  
   
Don't Forget to add Permission in AndroidManifest.XML

AndroidManifest.xml
 <uses-permission android:name="android.permission.INTERNET"/>  
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

 
Follow us for more posts like this, 
Subscribe to Harpreet studio on Youtube  
Like Harpreet Studio on Facebook  
Follow me on Instagram 

No comments