Friday, June 14, 2019

Google Signin using firebase

Google Sign-in  is the best method to authenticate a user .You need firebase account to  integrate google sign-in in your project. In the following tutorial i will teach you how to integrate the google sign-in.

1.  Connect firebase to android studio

     In your android studio
     Click on tools---->firebase--->Assistance dialog will open on the right

1.1 Click on Authentication



1.2 Press connect  to firebase




1.3 Press add firebase authentication to app and accept all the changes 
1.4 Open firebase console in browser and enable Google sign-in  from sign-in options



2. Integrating the code

Manifest file
 Add internet permission in manifest file

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


Java file

package com.vishalsingh.practice;
import android.content.Intent;import android.support.annotation.NonNull;import android.support.design.widget.Snackbar;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.Auth;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.GoogleSignInApi;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.common.api.GoogleApiClient;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 LoginActivity extends AppCompatActivity {
    private FirebaseAuth mAuth;    SignInButton signInButton;    GoogleSignInClient mGoogleSignInClient;    private static final int RC_SIGN_IN = 9001;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_login);
        mAuth = FirebaseAuth.getInstance();        signInButton = findViewById(R.id.signinbutton);
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        signInButton.setOnClickListener(new View.OnClickListener() {
                                            @Override                                            public void onClick(View view) {
                                                signin();                                            }
                                        });

    }

    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);
        
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);            try {
                GoogleSignInAccount account = task.getResult(ApiException.class);                firebaseAuthWithGoogle(account);            } catch (ApiException e) {
                /
                Toast.makeText(this,"", Toast.LENGTH_SHORT).show();               
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        //   Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            
                            FirebaseUser user = mAuth.getCurrentUser();                            Toast.makeText(LoginActivity.this, "user signed in", Toast.LENGTH_SHORT).show();                          
                        } else {
                            Toast.makeText(LoginActivity.this, "login failed", Toast.LENGTH_SHORT).show();                            

                        
                    }
                });    }
    @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, NavigationActivity.class));        }
    }
}

Xml  file

<?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=".LoginActivity">
    <com.google.android.gms.common.SignInButton        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/signinbutton"
        app:layout_constraintTop_toTopOf="parent"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent">
    </com.google.android.gms.common.SignInButton>


</android.support.constraint.ConstraintLayout>
NOTE:   In case of error make sure the following dependencies are present in build gradle

implementation 'com.google.firebase:firebase-core:16.0.0'implementation 'com.google.firebase:firebase-auth:17.0.0'implementation 'com.google.android.gms:play-services-auth:16.0.1'

No comments:

Alert Dialog Box

Alert Dialog Box Android AlertDialog   can be used to display the dialog message with OK and Cancel buttons. It can be used to inter...