Connect with us

Hi, what are you looking for?

Latest

Android Automatic SMS Verification

Android Automatic SMS Verification

In this article I will show you how to implement automatic SMS verification using the SMS Retriever API. Thanks to the SMS Retriever API, you can automatically check SMS messages in your application without the need for additional authorizations.

Contents

  • Demonstration of automatic verification of SMS applications
  • Introduction
  • Why use the SMS Retriever API?
  • Understand the SMS verification process
  • Implementation stepSupply the class dependence to the demand level
  • Get personalized content from your phone
  • SMS start release
  • Creation of a receiver for sending SMS messages
  • Registration of the SMS receiver in the Android Manifesto
  • Submit a request to the WBS
  • Retrieve the SMS format and the verification code from the sender of the SMS message.
  • Test the demo application
  • What you need to do
  • Technology used
  • Conclusion

1. AppDemonstration of automatic SMS verification

2. Introduction

I have explained the step by step process of implementing automatic SMS authentication in your Android application. Before we do that, let’s take a look at the SMS verification process.

Android Automatic SMS Verification

Source – Google

The figure above gives you an idea of the clarity of SMS message verification.

3. Why should you use SMS Retriever API?

Google is going to make important political changes. From the 19th. In January 2019, Google removed all applications under CALL_LOG and READ_SMSfrom the read-only memory.

4. Understanding the SMS verification process

In the past, when a user had to connect to the Android application on the Android platform, he had to enter a mobile phone number to receive OTP. You then grant READ_SMS authorization for the SMS reader application. Google has recently made some important policy changes. The Android platform now withdraws this authorization for data security reasons. You must now copy the code you received by SMS. Go back to the application and enter this code manually to log in.

To overcome this process, Google has introduced an SMS retrieval API to automatically receive the verification code sent by SMS in the application. This means that the user did not have to enter the code manually each time. Let’s follow this step to set up automatic SMS authentication in the Android application.

5. Implementation phase

I will now explain step by step the process of implementing automatic SMS authentication in the Android application.

5.1 Addition of the dependency level to annex

Add the following library to the build.gradle level application to integrate the SMS Retriever API into your project

implementation fileTree(dir: ‘libs’, including: [‘*.jar’])

the implementation of androidx.appcompat:appcompat:1.0.2

Implementing the com.android.support.constraint:constraraint-layout:1.1.3.

// lib for SMS verification (Telephone Auth)

Introduction of com.google.android.gms:play services-auth:17.0.0.

Introduction of com.google.android.gms: play services-auth-api-phone: 17.0.0.

test performance junit. Junit: 4.12

Execution of androidTest ‘com.android.support.test:runner:1.0.2’.

Implementation of androidTest com.android.support.test.espresso:espresso-core:3.0.2.

Dependencies {fileTree(dir: ‘libs’ implementation, including: [‘*.jar’]) ‘androidx.appcompat:appcompat:1.0.2’ implementation ‘com.android.support.constraint:limitraint-layout:1.1.3’ // lib for SMS authentication (Phone Auth) implementation ‘com.google.android.gms:play-services-auth:17’.0.0 Implementation of com.google.android.gms: play-services-auth-api-phone: 17.0.0 test Implementation of junit: 4.12 androidTest Implementation of com.android.support: test: runner: 1.0.2 androidTest Implementation of com.android.support.test.espresso: espresso-core: 3.0.2 }.

androidx.appcompat:appcompat:1.0.2 executingcom.android.support.constraint:constraint-layout:1..1.3/// lib for SMS authentication (Phone Auth) implementation of ‘com.google.android.gms:play-services-auth:17.0.0’implementation of ‘com.google.android.gms:play-services-auth-api-phone:17.0.0’.

testImplementation ‘junit:junit:4.12’
androidTestImplementation ‘com.android.support:test:runner:1.0.2’
androidTestImplementation ‘com.android.support.test.test.test.espresso:espresso-core:3.0.2’
}

5.2 Extract custom content from yourphone

Get a phone number from the device by noting to perform this next step

  • Google APIClient configuration

// Install the Google api client to get a hint/

mGoogleApiClient = new GoogleApiClient.Builder(this)

.addConnectionCallbacks(this)

.enableAutoManage (this, this)

.addApi(Auth.CREDENTIALS_API)

//set google api client for requesting mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this, this) .enableAutoManage(this, this) .addApi(Auth.CREDENTIALS_API) .build() ;

//set google api client for requesting
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.enableAutoManage(this, this)
.addApi(Auth.CREDENTIALS_API)
.build() ;

  • Get a number available in the user’s phone

public void getHintPhoneNumber() {

NoteRequest NoteRequest =

new HintRequest.Builder()

.setPhoneNumberIdentifierSupported(true)

Pending mIntent = Auth.CredentialsApi.getHintPickerIntent(mGoogleApiClient, hintRequest) ;

startIntentSenderForResult(mIntent.getIntentSender(), RESOLVE_HINT, null, 0) ;

} catch (IntentSender.SendIntentException e) {

public void getHintPhoneNumber() { HintRequest hintRequest = new HintRequest.Builder() .setPhoneNumberIdentifierSupported(true) .build(); PendingIntent mIntent = Auth.CredentialsApi.getHintPickerIntent(mGoogleApiClient, hintRequest); try { startIntentSenderForResult(mIntent.getIntentSender(), RESOLVE_HINT, null, 0, 0); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); } }.

public void getHintPhoneNumber() {
HintRequest hintRequest =
new HintRequest.Builder()
.setPhoneNumberIdentifierSupported(true)
.build();
PendingIntent mIntent = Auth.CredentialsApi.getHintPickerIntent(mGoogleApiClient, hintRequest);
try {
startIntentSenderForResult(mIntent.getIntentSender(), RESOLVE_HINT, null, 0, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}.
}

  • Get the number selected in OnActivityResult

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

super.onActivityResult (RequestCode, ResultCode, Data) ;

// The result, if we need a reference number. //

if (requestCode == RESOLVE_HINT) {

as (resultCode == activity.RESULT_OK) {

Account = data.getParcelableExtra(proof of permission.EXTRA_KEY) ;

// credential.getId(); <— You must process the sequence of numbers

inputMobileNumber.setText(credential.getId()) ;

Write the secure area onActivityResult (int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); //Result, if we have the index number as (requestCode == RESOLVE_HINT) { as (resultCode == Activity.RESULT_OK) { Credential = data.getParcelableExtra(Credential.EXTRA_KEY); // Credential.getId(); <— we need to process the entry line of the mobileNumber.setText(Credential.getId()); } } }.

@Override
protected void onActivityResult (int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Result, if we need index number
as (requestCode == RESOLVE_HINT) {
as (resultCode == Activity.RESULT_OK).

Credential = data.getParcelableExtra(credential.EXTRA_KEY);
// credential.getId(); <— the phone number string
inputMobileNumber.setText(credential.getId());
}.
}
}.

5.3 Initiating the SMS call

After the user has sent the phone, we need to start the SMS search.

public null startSMSListener() {

SmsRetrieverClient mClient = SmsRetriever.getClient(this) ;

Task mTask = mClient.startSmsRetriever() ;

mTask.addOnSuccessListener(new OnSuccessListener() {

Check the public vacuum for Void aVoid

layoutEnter.setVisibility(View.GONE) ;

layoutVerify.setVisibility (View.Visible) ;

Toast.makeText(MainActivity.this, SMS Retriever start, Toast.LENGTH_LONG).show() ;

mTask.addOnFailureListener(new OnFailureListener() {)

Cancel public nullity in case of failure (@NonNull Exception e) {

Toast.makeText(MainActivity.this, Error, Toast.LENGTH_LONG).show() ;

public invalid startSMSListener() { SmsRetrieverClient mClient = SmsRetriever.getClient(this); Task mTask = mClient.startSmsRetriever(); mTask.addOnSuccessListener(new OnSuccessListener() { @ delete public empty onSuccess(Void aVoid) { layoutInput.setVisibility(View.GONE); layoutVerify.setVisibility(View).VISIBLE); Toast.makeText(MainActivity.this, SMS Retriever start, Toast.LENGTH_LONG).show(); }. ); mTask.addOnFailureListener(new OnFailureListener() { @ Overwrite public blank onFailure(@NonNull Exception e) { Toast.makeText(MainActivity.this, Error, Toast.LENGTH_LONG).show(); } ; *). }) ; }

public invalid startSMSListener() {
SmsRetrieverClient mClient = SmsRetriever.getClient(this);
Task mTask = mClient.startSmsRetriever();
mTask.addOnSuccessListener(new OnSuccessListener() {
@Clarified public empty onSuccess(Empty aVoid) {
layoutEnter.setVisibility(View.GONE);
layoutVerify.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, SMS Retriever start, Toast.LENGTH_LONG).show();
}.
});
mTask.addOnFailureListener(new OnFailureListener() {
@Overwrite public blank onFailure(@NonNull Exception e)). {
Toast.makeText(MainActivity.this, Error, Toast.LENGTH_LONG).show();
}
});
}.

5.4 Creating a receiver for SMS messages

Create a broadcast receiver to receive SMS from the SMS Retriever API

Package com.wave.smsverification.receiver;

Import android.content.BroadcastReceiver ;

import android.content.context ;

Importing android content ;

Import the android.os package;

com.google.android.gms.auth.api.phone.SmsRetriever ;

com.google.android.gms.common.api.commonStatusCodes ;

com.google.android.gms.common.api.status;

Import com.wave.smsverification.OtpReceived interface

* Created on : 21 May 2019

public SmsBroadcastReceiver class SmsBroadcastReceiver expands BroadcastReceiver {

End-of-character private static sequence TAG = SmsBroadcastReceiver ;

Otp reception interface Otp reception interface = zero ;

public invalid setOnOtpListeners(OtpReceivedInterface otpReceiveInterface) {

this.otpReceiveInterface = otpReceiveInterface ;

@Define public nullity toGet(context, intention) {

Log.d(DAY, onReceive: ) ;

if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction()) {

Bundle extras = intent.getExtras() ;

Status mStatus = (Status) extraas.get(SmsRetriever.EXTRA_STATUS) ;

Change (mStatus.getStatusCode()) {

the CommonStatusCodes.SUCCESS case:

// Receive the contents of the SMS message.

Message string = (string) extraas.get(SmsRetriever.EXTRA_SMS_MESSAGE) ;

Log.d(TAG, onReceive: error + message) ;

as (otpreceived interface != zero) {

String otp = message.replace(<#>) Your otp code : , ) ;

otpReceiveInterface.onOtpReceived(otp) ;

the CommonStatusCodes.TIMEOUT case:

// Waiting for a text message (5 minutes).

Log.d(DAY, onReceive:);

as (otpreceived interface != zero) {

otpReceiveInterface.onOtpTimeout() ;

package com.wave.smsverification.receiver; import android content.BroadcastReceiver; import android content.Context; import android content.intentional; import android.os.bundle; import android util.log; import com google.android gms.auth.api.phone.SmsRetriever.com.google.android.gms.common.api.commonStatusCodes.import; com.google.android.gms.common.api.Status.import; com.wave.smsverification.interfaces.OtpReceivedInterface.import; /** * Created on : May 21, 2019 * Author : AndroidWave */ public SmsBroadcastReceiver class SmsBroadcastReceiver expands BroadcastReceiver { private static end string TAG = SmsBroadcastReceiver; OtpReceivedInterface otpReceiveInterface = null; public invalid setOnOtpListeners(OtpReceivedInterface otpReceiveInterface) { dit.otpReceiveInterface = otpReceiveInterface; } @Define a public spaceReceive { Log.d(Tag, onReceive: ); if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction()). {Package extras = intent.getExtras(); Status mStatus = (Status) extras.get(SmsRetriever.EXTRA_STATUS); Switch (mStatus.getStatusCode()) {Case CommonStatusCodes.}UCCESS : // Receive the content of the SMS’ String message = (String) extraas.get(SmsRetriever.EXTRA_SMS_MESSAGE); Log.d(TAG, onReceive: Error +message); if (otpReceiveInterface != { String otp = message.replace(<#> your otp code: , ); otpReceiveInterface.onOtpReceived(otp); } Pause; case CommonStatusCodes.TIMEOUT : // Waiting for an SMS with timer (5 minutes) Log.d(TAG, onReceive: Error); if (otpReceiveInterface != null) { otpReceiveInterface.onOtpTimeout(); }. Pause; } }

Package com.wave.smsverification.receiver;

Import android.content.BroadcastReceiver; import
android.content.Context; import
android.content.intentional; import
android.os.bundle; import
android.util.Log; import
com.google.android.gms.auth.phone.SmsRetriever;
-Import of com.google.android.gms.common.api.commonStatusCodes;
-Import of com.google.android.gms.common.api.Status;
-Import of com.wave.smsverification.interfaces.OtpReceivedInterface ;

/**
* Created: 21 May 2019
* Author : AndroidWave
*/
public SmsBroadcastReceiver class SmsBroadcastReceiver expands BroadcastReceiver {
private static end string TAG = SmsBroadcastReceiver;
OtpReceivedInterface otpReceiveInterface = null ;

public invalid setOnOtpListeners(OtpReceivedInterface otpReceiveInterface) {
this.otpReceiveInterface = otpReceiveInterface;
}

@Define a public onReceive(context, intention) {
Log.d(Tag, onReceive: );
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction()). {
Additional Package = intention.getExtras();
Additional Package mStatus = (SmsRetriever.EXTRA_STATUS) ;

Change (mStatus.getStatusCode())// Receive the contents of the SMS message.

Message line = (String) extraas.get(SmsRetriever.EXTRA_SMS_MESSAGE);
Log.d(TAG, onReceive: Error +Message);
if (otpReceiveInterface != null) {
String message otp = message.replace(<#> Your otp code: , );
otpReceiveInterface.onOtpReceived(otp);
} Break
; case
CommonStatusCodes.TIMEOUT :
// Waiting for an SMS with timer (5 minutes)Log.d(TAG, onReceive: Error);if (otpReceiveInterface != null) {otpReceiveInterface.onOtpTimeout();}break;}}}}break.

Create an auditor to send the WBS to an activity or fragment

Package com.wave.smsverification.interfaces;

* Created on : 21 May 2019

receive public OtpInterface {

Empty onOtpReceive(String otp) ;

Package com.wave.smsverification.interface; /** * Created on : 21. May 2019 * from : AndroidWave */ public interface OtpReceived interface { invalid onOtpReceived(String otp); invalid onOtpTimeout(); }

Package com.wave.smsverification.interfaces;

/**
* Created: 21 May 2019
* Author : AndroidWave
*/
public OtpReceived interface {
null and void onOtpReceived(String otp);
null and void onOtpTimeout();
}.

5.6 Registration of the SMS receiver in the Androidmanifest

Open the Android manifest and save the receiver with the intent filter.

android: name=.receiver.SmsBroadcastReceiver

.

android:name=.receiver.SmsBroadcastReceiver
android:export=true>



.

5.7 Open the file activity_main.xml and enter the followingcode

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

android: orientation=vertical

tools:context=.mainActivity

android: [email protected]+id/getOTPLayout

android: layout_width=match_parent

android: layout_height=wrap_content

android: layout_marginBottom=24dp

android: visibility=visible

android:[email protected]+id/picture display

android: layout_width=wrap_content

android: layout_height=wrap_content

android: layout_marginEnd=8dp

android: layout_marginStart=8dp

android: layout_marginTop=8dp

app:layout_constraintEnd_toEndOf=higher

app:layout_restrictionHorizontal_preload=0.498

app:layout_constraintStartOf=higher

app:layout_constraintTop_toTopOf= higher

app:[email protected]/otp

android: [email protected]+id/editTextInputMobile

android: layout_width=0dp

android: layout_height=wrap_content

android: layout_marginEnd=16dp

android: layout_marginStart=16dp

android: layout_marginTop=16dp

android: hint=9166964412

android: inputType=Phone

app:layout_constraintEnd_toEndOf=higher

app:layout_constraintStartOf=higher

app:[email protected]+id/textView2

android: [email protected]+id/buttonGetOTP

android: layout_width=wrap_content

android: layout_height=wrap_content

android: layout_marginBottom=16dp

android: layout_marginEnd=8dp

android: layout_marginStart=8dp

android: layout_marginTop=24dp

android: [email protected]/colorAccent

android: paddingLeft=16dp

android: paddingRight=16dp

android: textAllCaps=bath

app:layout_constraintBottom_toBottomOf=parent

app:layout_constraintEnd_toEndOf=higher

app:layout_constraintStartOf=higher

app:[email protected]+id/editTextInputMobile

android:[email protected]+id/textView2

android: layout_width=wrap_content

android: layout_height=wrap_content

android: layout_marginEnd=8dp

android: layout_marginStart=8dp

android: layout_marginTop=16dp

android:text= Enter your mobile phone number

app:layout_constraintEnd_toEndOf=higher

app:layout_constraintStartOf=higher

app:[email protected]+id/imageView

android: [email protected]+id/verifyOTPLayout

android: layout_width=match_parent

android: layout_height=wrap_content

android: layout_marginBottom=24dp

Android: Visibility = gone

android:[email protected]+id/picture display2

android: layout_width=wrap_content

android: layout_height=wrap_content

android: layout_marginEnd=8dp

android: layout_marginStart=8dp

android: layout_marginTop=8dp

app:layout_constraintEnd_toEndOf=higher

app:layout_restrictionHorizontal_preload=0.498

app:layout_constraintStartOf=higher

app:layout_constraintTop_toTopOf= higher

app:[email protected]/otp

android: [email protected]+id/edTextOTP

android: layout_width=wrap_content

android: layout_height=wrap_content

android: layout_marginEnd=16dp

android: layout_marginStart=16dp

android: layout_marginTop=16dp

android: inputType=Phone

app:layout_constraintEnd_toEndOf=higher

app:layout_constraintStartOf=higher

app:[email protected]+id/textView

android: [email protected]+id/buttonCheck

android: layout_width=wrap_content

android: layout_height=wrap_content

android: layout_marginBottom=16dp

android: layout_marginEnd=8dp

android: layout_marginStart=8dp

android: layout_marginTop=24dp

android: [email protected]/colorAccent

android: paddingLeft=16dp

android: paddingRight=16dp

android: textAllCaps=bath

app:layout_constraintBottom_toBottomOf=parent

app:layout_constraintEnd_toEndOf=higher

app:layout_constraintStartOf=higher

app:[email protected]+id/editTextOTP

android: [email protected]+id/text display

android: layout_width=wrap_content

android: layout_height=wrap_content

android: layout_marginEnd=8dp

android: layout_marginStart=8dp

android: layout_marginTop=16dp

android:text=Please enter the WBS that runs on

app:layout_constraintEnd_toEndOf=higher

app:layout_constraintStartOf=higher

app:[email protected]+id/imageView2

[email protected]+id/getOTPLayout android:layout_width=match_parent android:layout_height=wrap_content android:layout_marginBottom=24dp android:visibility= visible > [email protected]+id/imageView android :layout_width=Wrap_content android:layout_height=Wrap_content android:layout_marginEnd=8dp android:layout_marginStart=8dp android:layout_marginTop=8dp app:layout_constraintEnd_toEndOf=parent app:layout_constraintHorizontal_bias=0.498 app:layout_constraintStart_toStartOf=parent app:layout_constraintTop_toTopOf=parent app:[email protected]/otp /> [email protected]+id/editTextInputMobile android :layout_width=0dp android:layout_height=wrap_content android:layout_marginEnd=16dp android:layout_marginStart=16dp android:layout_marginTop=16dp android:ems=10 android:gravity=center android:hint=9166964412 android :inputType=phone app:layout_constraintEnd_toEndOf=parent app:layout_constraintStart_toStartOf=parent app:[email protected]+id/textView2 />

You May Also Like