How to Read SMS and verify otp automatically in android

Mobile number verification is becoming an important part while developing an application. Main advantage of mobile number verification is that we can identify each user in our application uniquely. We can do mobile number verification by sending an otp to the mobile which is using our application.In this tutorial let us learn how to read sms automatically and automatically verify the otp in android.

Before starting implementation please read our Android beginners app development guide which explains all basics related to android app development including installing ,configuring Android studio.

Steps

  1. Implement the layout with edit text for receiving otp.
  2. Create a BroadcastReceiver for receiving sms.
  3. Implement the code for auto verification otp in your activity’s java file
  4. Register boradcast Reciever in AndroidManifest.xml
  5. Add permissions to AndroidManifest.xml

Implement the layout with edit text for receiving otp

First step is to create a layout screen with edittext for displaying the otp once the otp is recieved. To implement that just place the following code inside your layout file

<EditText
    android:id="@+id/ed_otp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Create a BroadcastReceiver for receiving sms

Next step is to create a BroadcastReceiver class. Create a file under java/your-package/ “IncomingSms.java”.

Whenever an sms comes it will get captured on onRecieve(context,intent) defined in the IncommingSms.java class .From the bundle you can extract the phone number and message body. The entire message body will contain some text attached with otp. Like “Your otp is 5555” .This format will depended upon what we are setting in gateway . So first you need to identify the format of sms and then using split string extract only otp.

Right now we have otp in our Broadcast reciever class and we want it to be used in activity which is used for verification. For that we need to sent a internal broadcast message using LocalBroadcastManager.

Here is the full code for IncomingSms.java

IncomingSms.java

public class IncomingSms extends BroadcastReceiver {

    // Get the object of SmsManager
    final SmsManager sms = SmsManager.getDefault();

    public void onReceive(Context context, Intent intent) {

        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();

        try {

            if (bundle != null) {

                final Object[] pdusObj = (Object[]) bundle.get("pdus");

                for (int i = 0; i < pdusObj.length; i++) {

                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody().split(":")[1];

                    message = message.substring(0, message.length()-1);
                    Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);

                    Intent myIntent = new Intent("otp");
                    myIntent.putExtra("message",message);
                    LocalBroadcastManager.getInstance(context).sendBroadcast(myIntent);
                    // Show Alert

                } // end for loop
            } // bundle is null

        } catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" +e);

        }
    }
}

Implement the code for auto verification of otp in your activity’s java file

In the above code there is a there is an internal broadcast receiver which will send the received otp to the activity. So for using it in activity we need to have some code to accept the internal broadcast message. For that first we need to have the following code in your onResume and onPause functions.

@Override
public void onResume() {
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
    super.onResume();
}

@Override
public void onPause() {
    super.onPause();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
}

Now add the following code in your class

private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equalsIgnoreCase("otp")) {
            final String message = intent.getStringExtra("message");
             your_edittext.setText(message);
            //Do whatever you want with the code here
        }
    }
};

Here you will get the otp code and you can do verification with your server. Please note that the message received will be different for different peoples like for example, may the entire sms will be “Your otp is 3344” which will be in the format which is set on your server. So from the entire message you need to extract the number part by splitting the string and only number you need to place inside edittext.

Register your Broadcast Receiver class in your AndroidManifest.xml

Since we have broadcast register class we need to register it in AndroidManifest.xml .For registering broadcast receiver class just add the following code tag in your AndroidManifest.xml under your application tag.

<receiver android:name="com.your-package.IncomingSms">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

Add permissions to AndroidManifest.xml

Since we need to use the broadcast message we need to get some permission from user. If your target api is greater 21 you need get the run time permission in which user have the choice to allow the app to use receive sms feature .If target is less than or equal to 21 you just need to add the following set of code inside your AndroidManifest.xml outside the application tag

<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 : If your target version is greater than 22 you need to request permissions at run time.Refer tutorial Request permission at run time in android, which will help you to learn how to request permission dynamically in android.

 

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

270 Comments

  1. hanuman October 27, 2018 Reply
  2. deepak October 17, 2018 Reply
  3. Akash September 18, 2018 Reply
  4. Akash Sharma September 16, 2018 Reply
  5. Akash September 16, 2018 Reply
  6. AKASH September 16, 2018 Reply

Add a Comment

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