Automatically Reading SMS To Verify OTP - Android Hire
Coding Tutorials

Automatically Reading SMS To Verify OTP

Vidhi Markhedkar
In the digital age, security and convenience often go hand-in-hand, particularly in the realm of online transactions. One of the most significant advancements in this area is the use of One-Time Passwords (OTPs) for verification.

A critical aspect of this process is the ability to automatically read SMS to verify OTPs. This functionality not only streamlines user verification processes but also adds an extra layer of security to mobile applications.

Instead of using third party libraries to auto fetch OTP from SMS Inbox ,we can easily do this using Broadcast Receiver. Broadcast receiver allows you to send or receive application events.

Steps To Automatically Reading SMS To Verify OTP

Step1: Open app > res > drawable

Create a new resource file

Add the following xml code to create a custom background






Step 2: Create a vector Image use any image clip art.

Open drawable > new > vector Asset

Step 3: Create Layout File for OTP Verification




	

    	

    	

    	

        	
    	

    	

Step 4: Create a new java class

java < com.example.smsotp < new< java class

Create single Broadcast Receiver i.e SmsReceive to listen to our incoming SMS

eg: sms received is Your OTP is : 4587, Then in above code we have split the complete message string in to 2 parts using “:” this special symbol.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.widget.EditText;

import androidx.annotation.RequiresApi;

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
   @RequiresApi(api = Build.VERSION_CODES.KITKAT)
   @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 splitting the sms using " : " symbol
           String otp = msg.split(": ")[1];
           editText.setText(otp);
       }
   }
}

Step 5: MainActivity.java

we send request to user to access sms and access the otp if permission is granted

import android.Manifest;
       import android.content.pm.PackageManager;
       import android.os.Bundle;
       import android.widget.EditText;
       import androidx.annotation.Nullable;
       import androidx.appcompat.app.AppCompatActivity;
       import androidx.core.app.ActivityCompat;
       import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
   EditText otpnumber;

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

       //we ask user permission to auto read sms
       requestsmspermission();
       otpnumber = (EditText) findViewById(R.id.edittext);
       new OTP_Receiver().setEditText(otpnumber);
   }

   private void requestsmspermission() {
       String smspermission = Manifest.permission.RECEIVE_SMS;
       int grant = ContextCompat.checkSelfPermission(this, smspermission);
       // to check if read SMS permission is granted or not
       if (grant != PackageManager.PERMISSION_GRANTED) {
           String[] permission_list = new String[1];
           permission_list[0] = smspermission;
           ActivityCompat.requestPermissions(this, permission_list, 1);
       }
   }
}

Steps 6: Add Listener i.e broadcast receiver in android manifest file undertag and also add user-permission inside




//add this code to ask permissions to access sms
   
   
   
   
   
//add the following receiver code
       
           
               
           
       
       
           
               
               
           
       
   

Alternative Way: Using SMS Retriever API

Google's SMS Retriever API is an efficient way to read SMS messages for OTP without requiring additional permissions. To use this API, follow these steps:

  1. Generate an App Hash: This unique hash is used to identify your app and should be included in your OTP message.
  2. Receive the OTP Message: Configure your app to listen for an incoming SMS that contains the OTP and your app hash.
  3. Extract the OTP: Once the SMS is received, extract the OTP from the message automatically.

Best Practices and Security Considerations

  • Privacy Compliance: Always adhere to privacy laws and regulations when accessing and handling SMS messages.
  • Timeout for OTP: Implement a timeout for the OTP validity to prevent unauthorized use.
  • Rate Limiting: To avoid abuse, limit the number of OTP requests a user can make within a certain time frame.

Conclusion

Automatically reading SMS to verify OTP in Android Studio is a game-changer in terms of security and user experience. By following the steps outlined above, developers can effectively implement this feature, ensuring both convenience and enhanced security for their app users.

Remember to keep user privacy and security at the forefront of your implementation strategy. With these tools and techniques, your Android app will not only be more secure but also provide a smoother and more user-friendly experience.

Vidhi Markhedkar's profile picture

Vidhi Markhedkar

Android developer and writer with a passion for creating innovative and user-friendly apps.

Related Posts

7 Top Samsung Galaxy Ring Alternatives for 2025

7 Top Samsung Galaxy Ring Alternatives for 2025

Tired of waiting for the Samsung Galaxy Ring to hit the market? You’re not alone. While the buzz around Samsung’s smart ring continues, a plethora of impressive alternatives is already available. These devices deliver advanced health tracking, stylish designs, and unique features that cater to various lifestyles. The current lineup of smart rings caters to […]

What Is Quiet Mode on Instagram and How to Activate It

What Is Quiet Mode on Instagram and How to Activate It

Ever wondered what Quiet Mode on Instagram is all about? This simple yet powerful Instagram feature helps you take a break from the constant buzz of notifications and focus on what truly matters. Whether you’re striving for better work-life balance, dedicating time to studying, or simply trying to disconnect from social media distractions, Quiet Mode […]

How to Make a Bed in Minecraft (Step-by-Step Guide)

How to Make a Bed in Minecraft (Step-by-Step Guide)

A bed in Minecraft is very important. It lets you skip the night and set your spawn point, so if you die, you will return to your bed instead of the original world spawn. This guide will show you how to gather materials, craft a bed, and set your spawn point. We’ll also show you how to customize your bed, build bunk […]

10 Best MMORPG Games For Android

10 Best MMORPG Games For Android

Not too long ago, MMORPG games and powerful gaming consoles were mostly exclusive to PCs. They required high-end graphics and systems to deliver their immersive gameplay. But times have changed. With the rise of gaming-oriented smartphones, you can now enjoy PC-like gaming experiences on your Android device. Thanks to these technological advancements and faster internet […]

Roblox: Fruit Battlegrounds codes (January 2025)

Roblox: Fruit Battlegrounds codes (January 2025)

Fruit Battlegrounds codes are all about getting more gems and help you to shoot up your rank in this One Piece anime-inspired game. This Fruit Battlegrounds was made by Popo developer. It is an action-packed game where players battle it out using unique fruit-based abilities. With constant updates, new fruits, and exciting challenges, it’s a fruity frenzy you won’t […]

Roblox: Ultimate Football Codes (January 2025)

Roblox: Ultimate Football Codes (January 2025)

Want to get some extra items for Ultimate Football in Roblox? You’ve come to the right place! Here’s the latest list of codes to help you score touchdowns and look stylish on the field. These codes offer free rewards such as coins and cosmetics to enhance your gameplay. What are Ultimate Football Codes? Ultimate Football […]

Roblox: Da Hood Codes (January 2025)

Roblox: Da Hood Codes (January 2025)

Are you a fan of Roblox games, in this article we will look at the Roblox Da Hood Codes for December 2024 that will help you unlock exclusive items, improve your gameplay and dominate the streets of Da Hood. You can feel that the game is inspired by the Grand Theft Auto series and there […]