Firebase Google SignIn in Android with FirebaseAuth


   Project code- CLICK ME

          what is firebase Auth?
Almost every app collects data of the user to give them access to use their app.there
are several reasons to collect data and creating user account one of the main reason to differentiate them and to give them access to what data they use they can save it.
so almost every have had different types of login. Some common examples of login are
login with facebook,loginwithG+, email login, signup with email, twitter login. So there are many auth providers in Android.
Firebase Auth is an Auth provider API by which you can set authentication in Android App by various Auth provides like facebook, twitter, G+, Gmail, email, GitHub.



Step 1-
make new Android Studio project.



Step2-
connect app with firebase by going
  Tools>firebase>Authantication



Step3-
Go firbase Console in browser and enable Google SignIn.

Step4-
 Add these lines in AndroidManifest.xml for taking Permission of internet.
       
        <uses-permission android:name="android.permission.INTERNET" />


Step5-

                              activity_main.xml(replace everything)



(  in place of tools:context="com.web.mad.google.MainActivity"  WRITE tools:context="YourPackagename.MainActivity "   )
 




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
tools:context="com.androidjson.firebasegooglelogin_androidjsoncom.MainActivity">

<com.google.android.gms.common.SignInButton
android:id="@+id/sign_in_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<Button
android:id="@+id/sign_out"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click Here To Sign Out"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:visibility="gone"
/>

<TextView
android:id="@+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text=""
android:gravity="center"
android:textSize="20dp"
android:textColor="#000"
/>

<TextView
android:id="@+id/textViewEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/textViewName"
android:text=""
android:gravity="center"
android:textSize="20dp"
android:textColor="#000"
/>

</RelativeLayout>


 
                         
                         
                                                  
                                                  
                                                  
                                                  
                           MainActivity.java 
 
      (Repace Every thing except First Line Because It is Package name)
 
 
 
 
package com.web.mad.google;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
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.ResultCallback;
import com.google.android.gms.common.api.Status;
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 {

// TAG is for show some tag logs in LOG screen.
public static final String TAG = "MainActivity";

// Request sing in code. Could be anything as you required.
public static final int RequestSignInCode = 7;

// Firebase Auth Object.
public FirebaseAuth firebaseAuth;

// Google API Client object.
public GoogleApiClient googleApiClient;

// Sing out button.
Button SignOutButton;

// Google Sign In button .
com.google.android.gms.common.SignInButton signInButton;

// TextView to Show Login User Email and Name.
TextView LoginUserName, LoginUserEmail;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


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

SignOutButton= (Button) findViewById(R.id.sign_out);

LoginUserName = (TextView) findViewById(R.id.textViewName);

LoginUserEmail = (TextView) findViewById(R.id.textViewEmail);

signInButton = (com.google.android.gms.common.SignInButton)findViewById(R.id.sign_in_button);

// Getting Firebase Auth Instance into firebaseAuth object.
firebaseAuth = FirebaseAuth.getInstance();

// Hiding the TextView on activity start up time.
LoginUserEmail.setVisibility(View.GONE);
LoginUserName.setVisibility(View.GONE);

// Creating and Configuring Google Sign In object.
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();

// Creating and Configuring Google Api Client.
googleApiClient = new GoogleApiClient.Builder(MainActivity.this)
.enableAutoManage(MainActivity.this , new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
} /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.build();


// Adding Click listener to User Sign in Google button.
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

UserSignInMethod();

}
});

// Adding Click Listener to User Sign Out button.
SignOutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

UserSignOutFunction();

}
});

}


// Sign In function Starts From Here.
public void UserSignInMethod(){

// Passing Google Api Client into Intent.
Intent AuthIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);

startActivityForResult(AuthIntent, RequestSignInCode);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == RequestSignInCode){

GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

if (googleSignInResult.isSuccess()){

GoogleSignInAccount googleSignInAccount = googleSignInResult.getSignInAccount();

FirebaseUserAuth(googleSignInAccount);
}

}
}

public void FirebaseUserAuth(GoogleSignInAccount googleSignInAccount) {

AuthCredential authCredential = GoogleAuthProvider.getCredential(googleSignInAccount.getIdToken(), null);

Toast.makeText(MainActivity.this,""+ authCredential.getProvider(),Toast.LENGTH_LONG).show();

firebaseAuth.signInWithCredential(authCredential)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> AuthResultTask) {

if (AuthResultTask.isSuccessful()){

// Getting Current Login user details.
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();

// Showing Log out button.
SignOutButton.setVisibility(View.VISIBLE);

// Hiding Login in button.
signInButton.setVisibility(View.GONE);

// Showing the TextView.
LoginUserEmail.setVisibility(View.VISIBLE);
LoginUserName.setVisibility(View.VISIBLE);

// Setting up name into TextView.
LoginUserName.setText("NAME = "+ firebaseUser.getDisplayName().toString());

// Setting up Email into TextView.
LoginUserEmail.setText("Email = "+ firebaseUser.getEmail().toString());

}else {
Toast.makeText(MainActivity.this,"Something Went Wrong",Toast.LENGTH_LONG).show();
}
}
});
}

public void UserSignOutFunction() {

// Sing Out the User.
firebaseAuth.signOut();

Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {

// Write down your any code here which you want to execute After Sign Out.

// Printing Logout toast message on screen.
Toast.makeText(MainActivity.this, "Logout Successfully", Toast.LENGTH_LONG).show();

}
});

// After logout Hiding sign out button.
SignOutButton.setVisibility(View.GONE);

// After logout setting up email and name to null.
LoginUserName.setText(null);
LoginUserEmail.setText(null);

// After logout setting up login button visibility to visible.
signInButton.setVisibility(View.VISIBLE);
}

}






5.Add Some LINE IN GRADLE BUILD IF ERROR OCCURE



compile 'com.android.support:appcompat-v7:25.1.0'
 compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha8'
compile 'com.google.firebase:firebase-core:11.0.4' 
compile 'com.google.firebase:firebase-auth:11.0.4'
 compile 'com.google.android.gms:play-services-auth:11.0.4'




(in future version my change like in place of 11.0.4 may change to 12.0.4 or something else u can check it by going firebase website)

Post a Comment

5 Comments

  1. These steps of Firebase Google SignIn in Android with FirebaseAuth is useful for connecting the firebase with google.Smartphones and, more recently, tablets are increasingly becoming the electronic devices of choice for more and more people, leaving software developers used to PC-sized application interfaces to grapple with a whole new outlook. Android & ios Developers in Denver is here to offer you the affordable and high-quality solutions.

    ReplyDelete
  2. Highly gainful and compelling information distributed by you. This turned out to be notable for me. Continue sharing. Professional Web design services are provided by W3BMINDS- Website development company in Lucknow.
    Website Design Agency | Website design company in Lucknow

    ReplyDelete