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<Void> mTask = mClient.startSmsRetriever() ;

mTask.addOnSuccessListener(new OnSuccessListener<Void>() {

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<Void> mTask = mClient.startSmsRetriever(); mTask.addOnSuccessListener(new OnSuccessListener<Void>() { @ 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<Void> mTask = mClient.startSmsRetriever();
mTask.addOnSuccessListener(new OnSuccessListener<Void>() {
@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

<action android:name=com.google.android.gms.auth.api.phone.SMS_RETRIEVE />

<Android receiver: name=.recipient.SmsBroadcastReceiver android:export=true> <internal filter> <android action: name=com.google.android.gms.auth.api.phone.SMS_RETRIEVE /> </internal filter>.

<receiver
android:name=.receiver.SmsBroadcastReceiver
android:export=true>
<internal filter>
<action android:name=com.google.android.gms.auth.api.phone.SMS_RETRIEVE />
</internal filter>
</receiver>.

5.7 Open the file activity_main.xml and enter the followingcode

<?xml Version=1.0 Encryption=utf-8? >

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

<cold.support.stress.support

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.support.constraint.ConstraintLayout>

<cold.support.stress.support

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

</android.support.constraint.ConstraintLayout>

<?xml version=1.0 encoding=utf-8? > <LinearLayout 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:gravity=center android:orientation=vertical tools:context=.MainActivity > <android.support.constraint.ConstraintLayout android:[email protected]+id/getOTPLayout android:layout_width=match_parent android:layout_height=wrap_content android:layout_marginBottom=24dp android:visibility= visible > <ImageView android:[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 /> <EditText 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: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 /> <button 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:text=Get OTP android:textAllCaps=Wrong android:textColor=#fff android:textSize=16sp app :layout_constraintBottomOf=parent app:layout_constraintEnd_toEndOf=parent app:layout_constraintStart_toStartOf=parent app:[email protected]+id/editTextInputMobile /> <TextView 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 in app:layout_constraintEnd_toEndOf=parent app:layout_constraintStart_toStartOf=parent app:[email protected]+id/imageView /> </android.support.constraint.ConstraintLayout> <android.support.constraint.ConstraintLayout android:[email protected]+id/verifyOTPLayout android:layout_width=match_parent android:layout_height=wrap_content android:layout_marginBottom=24dp android:visibility=gone > <ImageView android:[email protected]+id/imageView2 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 /> <Edit text android:[email protected]+id/editTextOTP android :layout_width=wrap_content 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= android :inputType=phone app:layout_constraintEnd_toEndOf=parent app:layout_constraintStart_toStartOf=parent app:[email protected]+id/textView /> <button 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:text=Check android:textAllCaps=Wrong android:textColor=#fff android:textSize=16sp app :layout_constraintBottomOf=parent app:layout_constraintEnd_toEndOf=parent app:layout_constraintStart_toStartOf=parent app:[email protected]+id/editTextOTP /> <TextView android :[email protected]+id/textView android:layout_width=wrap_content android:layout_height=wrap_content android:layout_marginEnd=8dp android:layout_marginStart=8dp android:layout_marginTop=16dp android :text=Add the resulting OB in app:layout_constraintEnd_toEndOf=parent app:layout_constraintStart_toStartOf=parent app:[email protected]+id/imageView2 /> </androidsupport.constraint.ConstraintLayout> </LinearLayout>.

<?xml version=1.0 encoding=utf-8?>
<LinearLayout
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:gravity=center
android:orientation=vertical
tools:context=.Main activity
>
<android.support.constraint.ConstraintLayout
android:[email protected]+id/getOTPLayout
android:layout_width=match_parent
android:layout_height=wrap_content
android:layout_marginBottom=24dp
android:visibility= visible
>.

<imageViewandroid:[email protected]+id/imageViewandroid:layout_wrap_contentandroid:layout_height=wrap_contentandroid:layout_marginEnd=8dpandroid:layout_marginStart=8dpandroid:layout_marginTop=8dpapp:layout_constraintEnd_toEndOf=parent app:layout_constraintHorizontal_bias=0.498app:layout_constraintStart_toStartOf=higher app:layout_constraintTop_toTopOf=higher app:[email protected]/otp/><EditTextandroid:[email protected]+id/editTextInputMobileandroid:layout_width=0dpandroid :layout_height=wrap_contentandroid:layout_marginEnd=16dpandroid:layout_marginStart=16dpandroid:layout_marginTop=16dpandroid:ems=10android:gravity=centerandroid:hint=9166964412android :hint=9166964412android:inputType=Phone app:layout_constraintEnd_toEndOf=parent app:layout_constraintStart_toStartOf=parent app:[email protected]+id/textView2/><keyandroid :[email protected]+id/buttonGetOTPandroid:layout_width=wrap_contentandroid:layout_height=wrap_contentandroid:layout_marginBottom=16dpandroid:layout_marginEnd=8dpandroid:layout_marginStart=8dpandroid:layout_marginTop=24dpandroid:layout:[email protected]/colorAccentandroid:paddingLeft=16dropandroid:paddingRight=16dropandroid:text=OTPtrieve android:textAllCaps=falseandroid :textColor=#fffandroid:textSize=16spapp:layout_constraintBottomOf=parent app:layout_constraintEnd_toEndOf=parent app:layout_constraintStart_toStartOf=parent app:[email protected]+id/editTextInputMobile/><TextViewandroid:[email protected]+id/textView2android:layout_width=wrap_contentandroid:layout_height=wrap_contentandroid:layout_marginEnd=8dpandroid:layout_marginStart=8dpandroid:layout_marginTop=16dpandroid:text=Enter your mobile phone number: layout_constraintEnd_toEndOf=pair tapp:layout_constraintStart_toStartOf=pair tapp:[email protected]+id/imageView/>

</android.support.constraint.com>
<android.support.constraint.com
android:[email protected]+id/verifyOTPLayout
android:layout_width=match_parent
android:layout_height=wrap_content
android:layout_marginBottom=24dp
android:visibility=gone
>

<ImageViewandroid:[email protected]+id/imageView2android:layout_wrap_contentandroid:layout_height=wrap_contentandroid:layout_marginEnd=8dpandroid:layout_marginStart=8dpandroid:layout_marginTop=8dpapp:layout_constraintEnd_toEndOf=parent app:layout_constraintHorizontal_bias=0.498app:layout_constraintStart_toStartOf=higher app:layout_constraintTop_toTopOf=higher app:[email protected]/otp/><EditTextandroid:[email protected]+id/editTextOTPandroid :layout_width=wrap_contentandroid:layout_height=wrap_contentandroid:layout_marginEnd=16dpandroid:layout_marginStart=16dpandroid:layout_marginTop=16dpandroid:ems=10android:gravity=centerandroid:hint=android :inputType=phoneapp:layout_constraintEnd_toEndOf=parent app:layout_constraintStart_toStartOf=parent app:[email protected]+id/textView/><ButtonAndroid:[email protected]+id/buttonVerifyandroid :layout_width=wrap_contentandroid:layout_wrap_width=wrap_contentandroid:layout_height=wrap_contentandroid:layout_marginBottom=16dpandroid:layout_marginEnd=8dpandroid:layout_marginStart=8dpandroid :layout_marginTop=24 dpandroid:[email protected]/colorAccentandroid:paddingLeft=16 dpandroid:paddingRight=16 dpandroid:text= Verificationandroid:textAllCaps=falseandroid :textColor=#fffandroid:textSize=16spapp:layout_constraintBottomOf=parent app:layout_constraintEnd_toEndOf=parent app:layout_constraintStart_toStartOf=parent app :[email protected]+id/editTextOTP/><TextViewandroid:[email protected]+id/textViewandroid:layout_wrap_contentandroid:layout_height=wrap_contentandroid:layout_marginEnd=8dpandroid :layout_marginStart=8dpandroid:layout_marginTop=16dpandroid:text=Enter OB toapp:layout_constraintEnd_toEndOf=pairtapp:layout_constraintStartOf=pairtapp:[email protected]+id/textView2/>

</android.support.constraint.constraintLayout>
</LinearLayout>

5.8 Start application WBS

Call the server API to request the OTP, and if the SMS listener starts successfully, listen to the listener to read the messages automatically.

// Listen to the SMS from the beginningSMSListener()

// listen to sms
startSMSListener() ;

5.9 Receipt of the SMS format and verification code in the SMS receiver.

This recipient receives the WBS and goes to the activity where you can perform the authentication.

Full source code MainActivity.java

Package com.wave.sms verification ;

android.app.import activity ;

Import android.app.PendingIntent ;

Importing android content ;

Import android.content.IntentFilter ;

Import android.content.IntentSender ;

Import the android.os package;

Constraint.android.support.android.import.and.support.ConstraintLayout

import android.view

Import and widget.widget.button

Import android.widget.editText ;

import android.widget.toast

androidx.annotation.non-zero import;

androidx.annotation.annotable import;

Import androidx.appcompat.appCompatActivity ;

import com.google.android.gms.auth.api ;

Import.com.google.android.gms.auth.api.credentials.Credential

com.google.android.gms.auth.api.credentials.HintRequest ;

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

Import com.google.android.gms.auth.api.phone.SmsRetrieverClient

com.google.android.gms.common.connectionResult ;

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

com.google.android.gms.tasks.OnFailureListener ;

com.google.android.gms.tasks.OnSuccessListener ;

com.google.android.gms.tasks.import;

Import com.wave.smsverification.OtpReceived interface

Import com.wave.smsverification.receiver.SmsBroadcastReceiver ;

The MainActivity public class expands AppCompatActivity, implements GoogleApiClient.ConnectionCallbacks,

Otp reception interface, GoogleApiClient. OnConnectionFailedListener {…

Google API mClient Google API Client ;

SMS Transmission Receiver SMS Transmission Receiver ;

private int RESOLVE_HINT = 2 ;

EditText inputMobile number, InputOtp ;

The btnGetOtp button, btnVerifyOtp ;

Constraint Layout LayoutCheck ;

protected hole onCreate(Bundle storedInstanceState) {

create super.onCreate(savedInstanceState) ;

setContentView(R.layout.activity_main) ;

// Init transmitter-receiver

mSmsBroadcastReceiver = new SmsBroadcastReceiver() ;

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

mGoogleApiClient = new GoogleApiClient.Builder(this)

.addConnectionCallbacks(this)

.enableAutoManage (this, this)

.addApi(Auth.CREDENTIALS_API)

mSmsBroadcastReceiver.setOnOtpListeners(this) ;

IntentFilter intentFilter = new IntentFilter() ;

intentionFilter.addAction(SmsRetriever.SMS_RETRIEVED_ACTION) ;

getApplicationContext().registerRecipient(mSmsBroadcast receiver, intFilter) ;

// get a mobile phone number from your phone

btnGetOtp.setOnClickListener(new view.OnClickListener()) {

Define a public space in the v {\an5}.

// Calling the server API for the OTP request and whether it was successfully launched

// Listening to SMS for automatic reading of lsitner messages

private void initiViews() {

inputMobileNumber = findViewById(R.id.editTextInputMobile) ;

inputOtp = findViewById(R.id.editTextOTP) ;

btnGetOtp = findViewById(R.id.buttonGetOTP) ;

btnVerifyOtp = findViewById(R.id.buttonVerify) ;

layoutInput = findViewById(R.id.getOTPLayout) ;

layoutVerify = findViewById(R.id.verifyOTPLayout) ;

@Overwrite public blank onConnected(@Nullable Bundle-Bundle) {

Checking the public void above Constantinople(int i) {…

Checking the public empty space for OtpReceive(String otp) {

Toast.makeText(this, Otp Receive + otp, Toast.LENGTH_LONG).show() ;

@Write the public blank onOtpTimeout() {

Toast.makeText(this, time-out, please resend, Toast.LENGTH_LONG).show() ;

@Overwrite public blank onConnection failed(@Non-zero connection result) {.

public null startSMSListener() {

SmsRetrieverClient mClient = SmsRetriever.getClient(this) ;

Task<Void> mTask = mClient.startSmsRetriever() ;

mTask.addOnSuccessListener(new OnSuccessListener<Void>() {

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 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) {

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 have to process the string of the phone number

inputMobileNumber.setText(credential.getId()) ;

com.wave.smsverification packet; import android.app.Activity; import android.app.PendingIntent; import android.content.IntentFilter; import android content.IntentSender; import android.os.Bundle; import android support.constraint.ConstraintLayout; import android.viewView.View; import android.widget.button; import android.button.widget.EditText; android.widget.Import Toast; import androidx annotation.NonNull; import androidx annotation.Annotable; import androidx.appcompat.appCompatActivity; import com.google.android gms.auth.api.gms.auth.api.credentials.Credential.import.com google.android.gms.auth.api.credentials.HintRequest.com google android gms.tasks.OnFailureListener.import.com google android gms.tasks.OnSuccessListener.import.com google android.gms.tasks.OnSuccessListener.import.com google android.gms.tasks.import.com.wave.smsverification.interfaces.OtpReceivedInterface; import.com.wave.smsverification.receiver.SmsBroadcastReceiver; MainActivity public class extends AppCompatActivity.connection, OtpReceivedInterface, GoogleApiClient implemented reminders.OnConnectionFailedListener { GoogleApiClient mGoogleApiClient; SmsBroadcastReceiver mSmsBroadcastReceiver; private int RESOLVE_HINT = 2; Enter EditTextMobileNumber, enterOtp ; Button btnGetOtp, btnVerifyOtp; ConstraintLayout layoutInput, layoutVerify; @Overwrite protected blank onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); // Init-Broadcast receiver mSmsBroadcastReceiver = new SmsBroadcastReceiver(); // set google api client for hint request mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .enableAutoManage(this, this) .addApi(Auth.CREDENTIALS_API) .build(); mSmsBroadcastReceiver.setOnOtpListeners(this); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(SmsRetriever.SMS_RETRIEVED_ACTION); getApplicationContext().registerReceiver(mSmsBroadcastReceiver, intentFilter); // Get the mobile number from getHintPhoneNumber(); btnGetOtp.setOnClickListener(new view.OnClickListener() { @Overwrite public blank onClick(View v) { // Call the server API for the OTP request, and if successful, start // SMS-Listener to start the automatically read message lsitner startSMSListener(); }. ); } private void initViews() { inputMobileNumber = findViewById(R.id.editTextInputMobile); inputOtp = findViewById(R.id.editTextOTP); btnGetOtp = findViewById(R.)id.editTextOTP).id.buttonGetOTP); btnVerifyOtp = findViewById(R.id.buttonVerify); layoutInput = findViewById(R.id.getOTPLayout); layoutVerify = findViewById(R.id.verifyOTPLayout); } @Overwrite public space onConnected(@Undoable bundle bundle) { } @Overwrite public blank onConnectionSuspended(int i) { } @Define public space toOtpReceived(String otp) { Toast.makeText(this, Otp Received + otp, Toast.LENGTH_LONG).show(); inputOtp.setText(otp); }. @Cancel the public void using the OnOtpTimeout() function { Toast.makeText(this, Time out, please return Toast.LENGTH).show(); }. @Cancel public void onConnectionFailed(@NonNull ConnectionResult) { } public void startSMSListener() { SmsRetrieverClient mClient = SmsRetriever.getClient(this); Task<Void> mTask = mClient.startSmsRetriever(); mTask.addOnSuccessListener(new OnSuccessListener<Void>() { @OpmaakInput.setVisibility(View.GONE); layoutVerify.setVisibility(View.VISIBLE); Toast.makeText(MainActivity.this, start SMS retrieval, 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 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(); } }. 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) { als (data != null) { Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY); // credential.getId(); <— we need to process the input string of the phone number MobileNumber.setText(credential.getId()); } } } } }.

Package com.wave.sms verification ;

Import android.app.Activity; import android.app.PendingIntent; import android content.IntentFilter; import android content.IntentSender; import android.os.bundle; import android support.constraint.ConstraintLayout; import android.view.widgetButton;android.widget.importEditText;android.widget.importToast;androidx.annotation.nonImport Null;androidx.annotation.import Null;androidx.appcompat.app.import AppCompatActivity;com.google.android.gms.auth.api.Auth Import;com.google.android.gms.auth.api.credentials Import.references; import com.google.android.gms.auth.api.credentials.HintRequest; import com.google.android.gms.auth.api.phone.SmsRetriever; import com.google.android.gms.auth.api.phone.SmsRetrieverClient; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.task; import com.wave.smsverification.interfaces.OtpReceivedInterface; import com.wave.smsverification.receiver.SmsBroadcastReceiver ;

The MainActivity public class extends AppCompatActivity to implement GoogleApiClient.ConnectionCallbacks,
OtpReceivedInterface, GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient mGoogleApiClient;
SmsBroadcastReceiver mSmsBroadcastReceiver;
private int RESOLVE_HINT = 2;
EditText inputMobileNumber, inputOtp;
Button btnGetOtp, btnVerifyOtp;
ConstraintLayout layoutInput, layoutVerify ;

Write
protected blank onCreate(storedInstanceState bundle) {
super.onCreate(storedInstanceState);
setContentView(R.layout.activity_main) ;

initViews();
// init broadcast receiver
mSmsBroadcastReceiver = new SmsBroadcastReceiver() ;

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

mSmsBroadcastReceiver.setOnOtpListeners(this);
IntentFilter intentFilter = new IntentFilter();
intFilter.addAction(SmsRetriever.SMS_RETRIEVED_ACTION);
getApplicationContext().registerReceiver(mSmsBroadcastReceiver, intFilter) ;

// Get a mobile number from phone
getHintPhoneNumber();
btnGetOtp.setOnClickListener(new view).OnClickListener() {
@Overwrite public blank onClick(View v) {
// Call server API for OTP request and if successful start
// SMS-Listener to automatically read message lsitner
startSMSListener();
}
});
}.

private void initViews() {
inputMobileNumber = findViewById(R.id.editTextInputMobile);
inputOtp = findViewById(R.id.editTextOTP);
btnGetOtp = findViewById(R.id.editTextOTP).buttonGetOTP);
btnVerifyOtp = findViewById(R.id.buttonVerify);
layoutInput = findViewById(R.id.getOTPLayout);
layoutVerify = findViewById(R.id.verifyOTPLayout);
}.

@Overwrite public blank onConnected(@Nullable Bundle-Bundle) {

}

Checking the public void above Constantinople(int i) {…

}

@Cancel the public blank onOtpReceived(String otp) {
Toast.makeText(this, Otp Received + otp, Toast.LENGTH_LONG).show();
inputOtp.setText(otp);
}.

@Overwrite public blank onOtpTimeout() {
Toast.makeText(this, Time out, please resend, Toast.LENGTH_LENGTH).show();
}.

@Overwrite public blank onConnection failed(@Non-zero connection result) {.

}

public invalid startSMSListener() {
SmsRetrieverClient mClient = SmsRetriever.getClient(this);
Task<Void> mTask = mClient.startSmsRetriever();
mTask.addOnSuccessListener(new OnSuccessListener<Void>() {
@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();
}
});
}.

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();
}.
}

@
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) overwrite {
super.onActivityResult(requestCode, resultCode, data);
//Result, if we want a hint number
as (requestCode == RESOLVE_HINT) {
as (resultCode == Activity.RESULT_OK) {
if (data != null) {
Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
// credential.getId(); <— we need to process the string with the phone number
inputMobileNumber.setText(credential.getId());
}.

}
}
}
}

6. Testing a demo application

When an OTP request is received via the REST API, the server sends an OTP message to the device. You must respect the following message format.

The message format must be –.

Google has introduced a new OTP message format. Here is the format of the SMS

  • Prefix: <#>
    • The message should start with <#>.
  • Contents: Your PDA: 156367
  • Postfix: Lashing the application key from the key cabinet (debugging or unlocking), for example. T61bL03HCN8
    • The message must end with a hash code. It was obtained from the CAT LOG generated by the AppSignature Wizard. Based on this, the system forwards the message to the relevant application.

Test under example

<#> You are OTP: 156367 T61bL03HCN8

To get the code of the server part, follow the link.

  • https://developers.google.com/identity/sms-retriever/verify#generating_a_one-time_code
  • https://www.twilio.com/docs/sms/app-verification

7. How to get the MOT hash code to create SMS messages

Let’s create a class called AppSignatureHelper and insert the code below. It’s the easiest way to get the hash code. You can also generate with PDC. Once you have the hash code that deletes the helper class…

Package com.wave.smsverification.helper;

import android.content.context ;

Import android.content.contextWrapper ;

Import android.content.pm.PackageManager ;

android.content.pm.Import signature ;

import android.util.base64

Importing java.nio.charset.standard character sets ;

Importing java.security.MessageDigest ;

Import java.security.NoSuchAlgorithmException ;

Import java.util.ArrayList ;

* Created on : 21 May 2019

the AppSignatureHelper public class expands ContextWrapper {

private static end line TAG = AppSignatureHelper ;

Own static end line HASH_TYPE = SHA-256 ;

public static end int NUM_HASHED_BYTES = 9 ;

public static end int NUM_BASE64_CHAR = 11 ;

public AppSignatureHelper {

* Get all signatures for the application of the current package

public ArrayList<String> getAppSignatures() {

ArrayList<String> appCodes = new ArrayList<>() ;

// Get all signatures for the current package.

Line PackageName = getPackageName() ;

PackageManager packageManager = getPackageManager() ;

Signature[] Signature = packageManager.getPackageInfo(package name),

Batchmanager.GET_SIGNATURES).signatures ;

// Create a compatible hash for each signature

for (Signed: Signature) {

hashstring = hash(PackageName, Signature.toCharsString() ;

appCodes.add(string.format(%s, hash)) ;

} catch (PackageManager.NameNotFoundException e) {

Log.e (TAG, Can’t find package to get hash, e) ;

private string hash (string packet name, string signature) {

String applicationInfo = package name + + signature ;

MessageDigest messageDigest = MessageDigest.getInstance(HASH_TYPE) ;

messageDigest.update(appInfo.getBytes(default character set.UTF_8)) ;

byte[] hashSignature = messageDigest.digest() ;

// truncated in NUM_HASHED_BYTES

hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM_HASHED_BYTES) ;

Base64Hash string = Base64.encodeToString(hashSignature, Base64.NO_PADDING | Base64.NO_WRAP) ;

base64Hash = base64Hash.substring(0, NUM_BASE64_CHAR) ;

Log.d (TAG, String.format (pkg: %s — Hash: %s, packet name, base64Hash)) ;

capture (NoSuchAlgorithmException e) {

Log.e (TAG, Hash: NoSuchAlgorithm, e) ;

com.wave.smsverification.helper.package; import android.content.ContextWrapper; import android content.pm.PackageManager; import android content.pm.Signature; import android util.Base64; import android util.protocol; import java.nio.charset.standard character set; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.ArrayList; /** * Created on : 21. May 2019 * Author : AndroidWave */ public class AppSignatureHelper expands ContextWrapper { private static end string TAG = AppSignatureHelper; private static end string HASH_TYPE = SHA-256; public static end string int NUM_HASHED_BYTES = 9; public static end string int NUM_BASE64_CHAR = 11; public AppSignatureHelper(context) { super(context); }. /** Get all application signatures for the current package */ public ArrayList<String> getAppSignatures() { ArrayList<String> appCodes = new ArrayList<>(); try { // Get all application signatures for the current String packageName = getPackageName(); PackageManager packageManager = getPackageManager(); Signature[] signatures = packageManager.getPackageInfo(packagename, PackageManager.GET_SIGNATURES).signature; // For each signature, create a compatible hash for (Signature Signature: signature) { String hash = hash(packagename, signature.toCharsString()); as (hash != null) { appCodes.add(String.format(%s, hash)); }. } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, It is impossible to find the package to the hash…e); } return appCodes; } private static String hash(String packageName, String signature) { String appInfo = package name + + signature; try { MessageDigest messageDigest.getInstance(HASH_TYPE); messageDigest.update(appInfo.getBytes(StandardCharsets.UTF_8))); byte[] hashSignature = messageDigest.digest(); // truncated in NUM_HASHED_BYTES hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM_HASHED_BYTES); // encoded in Base64 String base64Hash = Base64.encodeToString(hashSignature, Base64.NO_PADDING | Base64.NO_WRAP); base64Hash = base64Hash.substring(0, NUM_BASE64_CHAR); Log.d(TAG, String.format(pkg: %s — hash: %s, PaketName, base64Hash)); return base64Hash; }. catch (NoSuchAlgorithmException e) { Log.e(TAG, hash:NoSuchAlgorithm, e); } return zero; }. }

Package com.wave.smsverification.helper;

-Import android.content.ContextWrapper;
-Import android.content.pm.PackageManager;
-Import android.content.pm.Signature;
-Import android.util.Base64;
-Import android.util.Log;
import java.nio.charset.standard character sets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Array ;

/**
* Created on: 21 May 2019
* Author : AndroidWave
*/
public class AppSignatureHelper expands ContextWrapper {

private static closing string TAG = AppSignatureHelper;
private static closing string HASH_TYPE = SHA-256;
public static closing string int NUM_HASHED_BYTES = 9;
public static closing string int NUM_BASE64_CHAR = 11 ;

public AppSignatureHelper(context) {
super(context);
}

/**
* Get all application signatures for the current
package */
public ArrayList<String> getAppSignatures() {
ArrayList<String> appCodes = new ArrayList<>() ;

try {
// All package signatures for the current
-string packageName = getPackageName();
PackageManager packageManager = getPackageManager();
Signature[] signature = packageManager.getPackageInfo(packageName,
PackageManager.GET_SIGNATURES) ;

// For each signature, create a
-compatible hash for (signature : signature) {
string hash = hash(packageName, signature.toCharsString());
if (hash != null) {
appCodes.add(String.format(%s, hash));
}
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, Can’t find the package to retrieve the hash, e);
}
returnable appCodes;
}

private static string hash {
String appInfo = packet name + + signature;
try {
MessageDigest messageDigest = MessageDigest.getInstance(HASH_TYPE);
messageDigest.update(appInfo.getBytes(default character sets.UTF_8)));
byte[] hashSignature = messageDigest.digest() ;

// truncated in NUM_HASHED_BYTES
hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM_HASHED_BYTES);
// encryption in Base64
Base64Hash string = Base64.EncodeToString(hashSignature, Base64.NO_PADDING | Base64.NO_WRAP);
base64Hash = base64Hash.substring(0, NUM_BASE64_CHAR) ;

Log.d(TAG, String.format(pkg: %s — hash: %s, packageName, base64Hash));
returns base64Hash;
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, hash:NoSuchAlgorithm, e);
}
returns zero;
}
} catch.

Calling up the getAppSignatures() methods in the onCreate() application

Package com.wave.sms verification ;

android.app import application ;

Import com.wave.smsverification.helper.AppSignatureHelper

* Created on : 21 May 2019

the public class SmsVerificationApp extends the application {

@Scribe the audience blankCreate() {

AppSignatureHelper appSignatureHelper = new AppSignatureHelper(this) ;

appSignatureHelper.getAppSignatures() ;

package com.wave.smsverification; import android.app.application; import com.wave.smsverification.helper.appSignatureHelper; /** * Created on : 21 May 2019 * Author : AndroidWave */ public class SmsVerificationApp expands the application { @overwrite public gap onCreate() { super.onCreate(); AppSignatureHelper appSignatureHelper = new AppSignatureHelper(this); AppSignatureHelper.getAppSignatures(); } }.

Package com.wave.sms verification ;

import android.app.application;
import com.wave.smsverification.helper.AppSignatureHelper ;

/**
* Created: 21 May 2019
* Author : AndroidWave
*/
public class SmsVerificationApp extends the application {
@overwrite public blank onCreate() {
super.onCreate();
AppSignatureHelper appSignatureHelper = new AppSignatureHelper(this);
appSignatureHelper.getAppSignatures();
}
}.

8. To do

  • Once you’re done, you’ll receive the hash code to remove the AppSignatureHelper class from your project before you start working or producing.
  • In Android, debugging and releasing the MOT have different hash codes. Make sure you get the version build hash code.

9. Technology used

A tool: Android Studio v3.3 with API 28 (Pie 9.0), SDK language
: Java, XML

Conclusion

With this Android training application we learned how to implement automatic SMS verification using the SMS Retriever API. Later I will also download the MOT and the source code, so you can get the sources for this demo application.

Search solution code

If you have any comments or questions, please fill them out below. If you would like to integrate automatic SMS verification into your Android project, please contact us.

 

 

 android sms verification,sms verification code

You May Also Like