Auto Read OTP with Runtime Permissions in Android

This tutorial will walk you through the steps required to automatically read the SMS for retrieving an OTP and auto-verify it.


Create a new Android project with MainActivity and its layout as activity_main.xml. Once the project sets up, right click on your package folder go to New -> Other -> Broadcast Receiver. Enter the name of our Broadcast Receiver class as “SmsBroadcastReceiver” and click on Finish.

You’ll see the following class is created inside your package.

public class SmsBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {




Create a new Interface class by right clicking on your package -> New -> Java class. Then enter the name as “SmsListener” and select the kind as Interface. Click on Finish.

Open the SmsListener class and enter the following method inside it.

public interface SmsListener {
void messageReceived(String sender, String messageText);


This interface is used to communicate between Broadcast Receiver and MainActivity.


Now, go back to SmsBroadcastReceiver class and enter the following code inside it.

The intent contains PDU objects (Protocol Data Unit), which is a protocol for transfer of SMS messages in telecoms. We obtain an array of these messages that were sent to to our receiver by system.

Iterating all these, we create a SmsMessage object using createFromPdu() method as shown. smsMessage.getDisplayOriginatingAddress() gives us the sender number. smsMessage.getMessageBody() gives us the message text.


Add the following permissions in your AndroidManifest.xml.

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />

Note that for API level 23 and above, we need to ask permissions during runtime.



Go to MainActivity and add the following code.

That’s it. We can test our code now.


Run the app in emulator or a device and send an sms.You’ll be asked for runtime permissions if the android version is Marshmallow or above. Allow access to SMS by clicking Yes. After that, whenever you receive an SMS, you ll see the message in your logcat and a Toast.



admin Author

Leave a Reply

Your email address will not be published. Required fields are marked *