How to authenticate mobile number in android studio

 Dear developer,

if you have not connected your project to firebase already click on  Connect your project to Firebase

if you have to face any problems during connecting your project to firebase, click on How to connect the android project to firebase in android studio

for  login with the phone number from one activity to another activity, follow these steps for easy implementation,

Step: 1

 Add classpath and maven in the project-level module,
Click on project

Click on the build. Gradle




Note-: build. Gradle should have the same as below code
buildscript {
repositories {
google()
jcenter()
mavenCentral();
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.3"
classpath 'com.google.gms:google-services:4.3.10'
}
}

allprojects {
repositories {
google()
mavenCentral()
jcenter()
maven {
url "https://jitpack.io"
}


}
}

Step 2:

Add dependencies in an app-level module,
Click on android
Click on the build. Gradle


Note-: build. Gradle code same as below code

plugins {
id 'com.android.application'
}

android {
compileSdkVersion 30
buildToolsVersion "30.0.3"

defaultConfig {
applicationId "com.example.phoneauthentication"
minSdkVersion 19
targetSdkVersion 30
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}

dependencies {

implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
testImplementation 'junit:junit:'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

implementation 'com.github.joielechong:countrycodepicker:2.4.2'
implementation platform('com.google.firebase:firebase-bom:26.1.0')
    implementation 'com.google.firebase:firebase-auth'
 
}

Step : 3

This step recommend for beginners,

if you are a senior developer, you can skip this step,
Go to your android project, follow these steps-

Click on res

Click on Value
                                                                         ↓
                                                              Click on String.xml

you should add the below code in strings.xml

Note-: Below code may be different if you add a different string.
<resources>
<string name="app_name">phone authentication</string>
<string name="_1234567890">1234567890</string>
<string name="enter_your_valid_mobile_no">enter your valid mobile no</string>
<string name="Send_Otp">send otp</string>
<string name="Enter_otp">enter otp</string>
<string name="Submit">submit</string>
<string name="ReSend_Otp">resend otp</string>
<string name="Phone_verification">phone varification</string>
</resources>

Step : 4

Add below code in activity.xml

Click on activity.xml

<TextView
    android:id="@+id/phone_no"
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="@color/teal_700"
android:text="@string/Phone_verification"
tools:ignore="MissingConstraints" />

<RelativeLayout
android:orientation="horizontal"
android:id="@+id/mobile_layout"
android:layout_width="433dp"
android:layout_height="80dp"
android:layout_below="@id/phone_no"
tools:layout_editor_absoluteX="-22dp" >

<com.rilixtech.widget.countrycodepicker.CountryCodePicker
android:id="@+id/cpp"
android:layout_width="138dp"
android:layout_height="49dp"
android:digits="@string/_1234567890"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="2dp"
android:layout_marginTop="27dp"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="52dp"
tools:ignore="Autofill,LabelFor"
android:ems="10"
/>

<EditText
android:id="@+id/edit_Mobile_no"
android:layout_width="248dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginTop="12dp"
android:layout_marginEnd="68dp"
android:autofillHints="012345"
android:digits="+0123456789"
android:ems="10"
android:hint="@string/enter_your_valid_mobile_no"
android:inputType="phone"
android:maxLength="10"
android:maxLines="1"
app:layout_constraintEnd_toEndOf="parent"
tools:ignore="MissingConstraints" />

</RelativeLayout>

<Button
android:id="@+id/send_mobile_code"
android:layout_width="match_parent"
android:layout_height="52dp"
android:layout_below="@id/mobile_layout"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:layout_marginBottom="3dp"
android:background="@color/purple_700"
android:gravity="center"
android:text="@string/Send_Otp"
android:textColor="@color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintVertical_bias="0.182"
tools:ignore="MissingConstraints" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">

<EditText
android:id="@+id/enter_code"
android:layout_width="225dp"
android:layout_height="56dp"
android:layout_above="@+id/submit_mobile_code"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"

android:layout_marginTop="5dp"
android:layout_marginEnd="105dp"
android:layout_marginBottom="5dp"
android:autofillHints="@string/_1234567890"
android:digits="0123456789"
android:gravity="center"
android:maxLength="6"
android:hint="@string/Enter_otp"
android:inputType="numberPassword"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.308"
tools:ignore="MissingConstraints" />

<Button
android:id="@+id/submit_mobile_code"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="0dp"
android:layout_marginBottom="261dp"
android:background="@color/purple_700"
android:gravity="center"
android:text="@string/Submit"
android:textColor="@color/white"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/enter_code"
app:layout_constraintVertical_bias="0.266"
tools:ignore="MissingConstraints" />

<Button
android:id="@+id/Resend_mobile_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginTop="10dp"
android:layout_marginEnd="-2dp"
android:layout_marginBottom="186dp"
android:background="@color/teal_700"
android:gravity="center"
android:text="@string/ReSend_Otp"
android:textColor="@color/white"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/submit_mobile_code"
app:layout_constraintVertical_bias="0.182"
tools:ignore="MissingConstraints" />

</RelativeLayout>

Step :6

Add below code in MainActivity.java

                                Click on Mainactivity.java
                      

package com.example.phoneauthentication;

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

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.FirebaseException;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.rilixtech.widget.countrycodepicker.CountryCodePicker;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
TextView phone_text;
EditText mobile_no, enter_code;
Button button_continue, button_submit,resendotp;
FirebaseAuth firebaseAuth;
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
public String Varificationid,userphonenumber;
ProgressDialog progressDialog;
RelativeLayout relativeLayout;
CountryCodePicker countryCodePicker;
PhoneAuthProvider.ForceResendingToken resendingtoken;


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

// How to connect android project to firebase in android studio


if(FirebaseAuth.getInstance().getCurrentUser()!=null) {
startActivity(new Intent(getApplicationContext(), dashboardactivity.class));
}
else{
startActivity(new Intent(getApplicationContext(), MainActivity.class));

}
phone_text = findViewById(R.id.phone_no);
countryCodePicker=findViewById(R.id.cpp);
resendotp=findViewById(R.id.Resend_mobile_code);
resendotp.setEnabled(false);
relativeLayout=findViewById(R.id.mobile_layout);
mobile_no = findViewById(R.id.edit_Mobile_no);
countryCodePicker.registerPhoneNumberTextView(mobile_no);
enter_code = findViewById(R.id.enter_code);
button_continue = findViewById(R.id.send_mobile_code);
button_submit = findViewById(R.id.submit_mobile_code);
firebaseAuth = FirebaseAuth.getInstance();
button_continue.setVisibility(View.VISIBLE);

// How to connect android project to firebase in android studio

button_continue.setOnClickListener(v -> {
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
Toast.makeText(MainActivity.this, "You have rasistered already", Toast.LENGTH_LONG).show();
} else {
String phonenumber = mobile_no.getText().toString();
if (TextUtils.isEmpty(phonenumber.trim())) {
mobile_no.setError("Please enter valid phone no");
mobile_no.requestFocus();
}
userphonenumber = countryCodePicker.getFullNumberWithPlus().replace("", "");
// userphonenumber=countryCodePicker+phonenumber;
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
.setActivity(MainActivity.this)
.setPhoneNumber(userphonenumber)
.setTimeout((long) 60, TimeUnit.SECONDS)
.setCallbacks(mCallbacks)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);

}
});


resendotp.setOnClickListener(v -> {
String phonenumber1=mobile_no.getText().toString();
if (TextUtils.isEmpty(phonenumber1.trim())){
mobile_no.setError("Please enter valid phone no");
mobile_no.requestFocus();
}
userphonenumber=countryCodePicker.getFullNumberWithPlus().replace("","");
PhoneAuthOptions options= PhoneAuthOptions.newBuilder(firebaseAuth)
.setActivity(MainActivity.this)
.setPhoneNumber(userphonenumber)
.setTimeout((long)60, TimeUnit.SECONDS)
.setCallbacks(mCallbacks)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);

});
button_submit.setOnClickListener(v -> {
String code = enter_code.getText().toString();
if(enter_code.toString().isEmpty() || enter_code.toString().length() < 6){
Toast.makeText(MainActivity.this,"Please enter valid Otp",Toast.LENGTH_LONG).show();
}
else {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(Varificationid, code);
if(enter_code.toString().matches(Varificationid)) {
authenticateuser(credential);
Intent intent=new Intent(MainActivity.this,dashboardactivity.class);
startActivity(intent);
}
else {
Toast.makeText(MainActivity.this,"Please enter valid Otp",Toast.LENGTH_LONG).show();
}

}
});
mCallbacks=new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
authenticateuser(phoneAuthCredential);
Intent intent=new Intent(MainActivity.this,dashboardactivity.class);
startActivity(intent);

}

@Override
public void onCodeAutoRetrievalTimeOut(@NonNull String s) {
super.onCodeAutoRetrievalTimeOut(s);
resendotp.setEnabled(false);
}

@Override
public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
Varificationid=s;
resendingtoken=forceResendingToken;
Toast.makeText(MainActivity.this,"Otp send",Toast.LENGTH_LONG).show();
relativeLayout.setVisibility(View.INVISIBLE);
button_continue.setVisibility(View.INVISIBLE);
button_submit.setVisibility(View.VISIBLE);
enter_code.setVisibility(View.VISIBLE);
resendotp.setVisibility(View.INVISIBLE);
resendotp.setEnabled(true);

}

@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
};
}


private void authenticateuser(PhoneAuthCredential phoneAuthCredential) {
progressDialog=new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Creating Account");
progressDialog.setMessage("Please wait.....");
progressDialog.show();
firebaseAuth.signInWithCredential(phoneAuthCredential).addOnSuccessListener(authResult -> {
String id= Objects.requireNonNull(authResult.getUser()).getUid();
progressDialog.dismiss();
Toast.makeText(MainActivity.this,"Login successfully",Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,dashboardactivity.class));
finish();
}).addOnFailureListener(e -> Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_LONG).show());
}

}



You could follow thease sites for phone authentication :
GeeksforGeeks to phone authentication
Stack overflow to Mobile number validation
Tutorialspoint for phone authentication
Firebase to phone authentication

Comments

Popular posts from this blog

How to connect android project to Firebase

How to create a new activity in existing android project in android studio

How to Create a Custom menu in android studio

How to create android project in android studio

How to add(Part-2) Video in FirebaseRecyclerAdapter in android studio

How to download google-services.json file from firebase

How to Add Like,Dislike button in video in android studio

How to create Layout Resource File in existing project in android studio

How to add Video(Part-1) in FirebaseRecyclerAdapter from Galllary..