Phone Authentication using Android with Firebase



Phone Authentication using Android with Firebase


Output Screen

   



Login First from Android Studio :




Connect with Firebase from Android Studio :



Then go to Authentication and select Email and Password Authentication :



Then perform two below process connect your app to Firebase and add Dependency after this go to google chrome and open Firebase console and make sure you are login with same gmail id :



Then select your project and go to Authentication in left side:



Then go to sign-in method and enable phone like below :




Now go to Android Studio :



In Gradle we have this dependency

implementation 'com.google.firebase:firebase-auth:16.0.5'


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<
ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/back_document" />

<
TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/ll"
android:layout_centerHorizontal="true"
android:layout_marginBottom="70dp"
android:text="Phone Authentication"
android:textColor="#fff"
android:textSize="30sp"
android:textStyle="bold"
android:typeface="serif" />

<
LinearLayout
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical">

<
EditText
android:id="@+id/mymobile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:background="@drawable/button"
android:hint="Enter Mobile Number"
android:inputType="number"
android:maxLength="10"
android:padding="20dp"
android:textColor="#fff"
android:textColorHint="#fff" />

<
EditText
android:id="@+id/myotp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:background="@drawable/button"
android:hint="OTP Number"
android:inputType="number"
android:maxLength="10"
android:padding="20dp"
android:textColor="#fff"
android:textColorHint="#fff" />


<
Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:layout_marginRight="20dp"
android:background="@drawable/button"
android:onClick="generate"
android:text="Generate"
android:textAllCaps="false"
android:textColor="#fff"
android:textStyle="bold"
android:typeface="serif" />


<
Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:background="@drawable/button"
android:onClick="verify"
android:text="Verify &amp; Login"
android:textAllCaps="false"
android:textColor="#fff"
android:textStyle="bold"
android:typeface="serif" />


</
LinearLayout>
</
RelativeLayout>



activity_home_page.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns: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=".HomePage">

<
ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/back_document" />

<
TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="#fff"
android:text="Welcome To Home Page"
android:textStyle="italic"
android:typeface="serif"
android:layout_centerHorizontal="true"
android:padding="20dp" />

<
TextView
android:id="@+id/mytext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="#fff"
android:typeface="serif"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:padding="20dp" />


<
Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:background="@drawable/button"
android:onClick="logout"
android:text="Logout"
android:textColor="#fff"
android:textStyle="bold" />

</
RelativeLayout>



button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<
stroke
android:width="1dp"
android:color="#fff" />
<
corners
android:bottomRightRadius="10dp"
android:topLeftRadius="10dp" />
</
shape>

 


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.phoneaunthentication">

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

<
application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<
activity android:name=".HomePage"></activity>
<
activity android:name=".MainActivity">
<
intent-filter>
<
action android:name="android.intent.action.MAIN" />

<
category android:name="android.intent.category.LAUNCHER" />
</
intent-filter>
</
activity>
</
application>

</
manifest>



MainActivity.java

package com.example.phoneaunthentication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;

import java.util.concurrent.TimeUnit;

public class MainActivityextends AppCompatActivity {
private EditText tmobile, totp;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks myCallbacks;
private FirebaseAuth mAuth;
private String verificationCode;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.
activity_main);
tmobile= findViewById(R.id.mymobile);
totp= findViewById(R.id.myotp);
firebaseLogin();

}


public void generate(View view) {
        String phone =
tmobile.getText().toString();
        Log.e(
"error", "+91" + phone);
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
        "+91" + phone,              // verify mobile number
        60,                              // duration of timeout
        TimeUnit.SECONDS,    // timeout unit
        MainActivity.this,       // CurrentActivity for callback
        myCallbacks);

}


public void verify(View view) {
        String otp = totp.getText().toString();

        PhoneAuthCredential credential = PhoneAuthProvider

        .getCredential(verificationCode, otp);

        SigninWithPhone(credential);

}


private void SigninWithPhone(PhoneAuthCredential credential) {
        mAuth.signInWithCredential(credential)

        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {

        @Override
        public void onComplete(@NonNullTask<AuthResult> task) {
        if (task.isSuccessful()) {
        Toast.makeText(MainActivity.
this, "Success", Toast.LENGTH_SHORT)

        .show();
        goToHomePage();
                }
            }

});

}

@Override
protected void onStart() {
super.onStart();
        FirebaseUser user =
mAuth.getCurrentUser();
        if (user != null) {
        //go to home page
        goToHomePage();
        }
}


private void firebaseLogin() {
        mAuth= FirebaseAuth.getInstance();
        myCallbacks= new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        

        @Override
        public void onVerificationCompleted(PhoneAuthCredentialphoneAuthCredential) {
        Log.e(
"error", phoneAuthCredential.toString());
        //get sms code from here
        totp.setText(phoneAuthCredential.getSmsCode());
}

        @Override
        public void onVerificationFailed(FirebaseException e) {
        Log.e(
"error", e.toString());
}

        @Override
        public void onCodeSent(String s, PhoneAuthProvider.ForceResendingTokenfrc) {
        super.onCodeSent(s, frc);
        verificationCode= s;
        Log.e(
"error", "code is sent");
        }
    };
}

HomePage.java


package com.example.phoneaunthentication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class HomePage extends AppCompatActivity {
private FirebaseAuth mAuth;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    setContentView(R.layout.
activity_home_page);
    mAuth= FirebaseAuth.getInstance();

    TextViewttext = findViewById(R.id.
mytext);
    FirebaseUser user =
mAuth.getCurrentUser();
    if (user != null) {
    ttext.setText(user.getDisplayName() +
"\n" + user.getEmail() + "\n" +                      user.getPhoneNumber());
        }
}

public void logout(View view) {
    FirebaseUser user =
mAuth.getCurrentUser();
    user =
null;
    mAuth.signOut();
    startActivity(
new Intent(this, MainActivity.class));
    finish();
    }

}



Lets see output in Firebase console Authentication :