Automatically SMS OTP reader using Broadcast Receiver in android studio
Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will build an android application that will be able in reading incoming message automatically in android to verify otp.
FINAL OUTPUT OF READING OTP AUTOMATICALLY
Video Tutorial on How to auto read otp in android using Breadcast Receiver.
At the end of this android tutorial your app will be able the read sms and fetch all the text in that sms and then it will copy the OTP from SMS and paste it in EditText box.
So let’s begin implementation of otp sms reader
Create a new Android Project
Ofcourse you need to create a new android project or open any existing android project
To do so go to File > New > New Project
Give a name as per you need in my case i have names my application as “Auto sms otp reader”
Create a custom background for EditText and a Vector Image
1. edittextbackground.xml
create a new xml file in drawable folder
res > drawable(right click) > New > Drawable resource file
a dialog box will appear on your screen as shown below
Then, Here you can select any kind of image clip Art.
Create a new Java Class names OTPReceiver
OTPReceiver.java
package com.example.autosmsotpreader;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.widget.EditText;
public class OTP_Receiver extends BroadcastReceiver {
private static EditText editText;
public void setEditText(EditText editText)
{
OTP_Receiver.editText=editText;
}
// OnReceive will keep trace when sms is been received in mobile
@Override
public void onReceive(Context context, Intent intent) {
//message will be holding complete sms that is received
SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
for(SmsMessage sms : messages)
{
String msg = sms.getMessageBody();
// here we are spliting the sms using " : " symbol
String otp = msg.split(": ")[1];
editText.setText(otp);
}
}
}
eg: sms received is Your OTP is : 4587, Then in above code i have split the complete message string in to 2 parts using “:” this special symbol.
Open AndroidManifest.xml file & add the uses permission
adding uses permission
add this 4 user-permission inside <manifest> here </manifest> tags
<!-- this are the permission need so that application can read sms -->
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_SMS"/>
Now, Add the following receiver OTPReceiver.java in manifest under <application> tag