Android Receive SMS And Verify OTP Automatically Tutorial

4

This tutorial helps you to read SMS automatically in our Android application. We will use a BroadcastReceiver to receive the messages and use textview to show message.

Nowadays, Applications usually use SMS texts for authentication purpose, like OTP (One-Time-Passwords), where a message is sent by the service-provider and it is automatically read by the application, verifying it. This flow helps user to save a lot of app switching from application to messenger app and then entering the authentication text to app again.





Create a new project

We are going to create a new android project. Go to File ⇒ New ⇒ New Projects in Android studio.

Add Permission In AndroidManifest.xml

We need to add Receive & Read SMS permission and also add Read Phone State Permission in the Android Manifest file to send, receive and read sms in our app.

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

Request Permission To User Manually

Above Android version 5.0 provide facility to request permission to user dynamically. Hence we will add code in MainActivity to request permission to user.

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (checkAndRequestPermissions()) {
            // carry on the normal flow, as the case of  permissions  granted.
        }
    }

    private  boolean checkAndRequestPermissions() {
         int permissionSendMessage = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.SEND_SMS);

        int receiveSMS = ContextCompat.checkSelfPermission(this, 
                    Manifest.permission.RECEIVE_SMS);

        int readSMS = ContextCompat.checkSelfPermission(this, 
                    Manifest.permission.READ_SMS);
        List<String> listPermissionsNeeded = new ArrayList<>();

        if (receiveSMS != PackageManager.PERMISSION_GRANTED) {
              listPermissionsNeeded.add(Manifest.permission.RECEIVE_MMS);
        }
        if (readSMS != PackageManager.PERMISSION_GRANTED) {
              listPermissionsNeeded.add(Manifest.permission.READ_SMS);
        }
        if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
              listPermissionsNeeded.add(Manifest.permission.SEND_SMS);
        }
        if (!listPermissionsNeeded.isEmpty()) {
              ActivityCompat.requestPermissions(this, 
                listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 
                     REQUEST_ID_MULTIPLE_PERMISSIONS);
              return false;
         }
         return true;
     }
}

Android allow_permission-min

Create MySMSBroadCastReceiver Java file

To create BroadCastReceiver, we need to create a java file named as MySMSBroadCastReceiver.java.

Add MySMSBroadCastReceiver in AndroidMenifest

To read SMS, we need to add Broadcast Receiver in the application section of AndroidMenifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.studytutorial.mycustomsmsreceiver">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".MySMSBroadCastReceiver" >
            <intent-filter android:priority="999" >
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

MySMSBroadCastReceiver Extends BroadcastReceiver

To read sms, We will extends BroadcastReceiver class in MySMSBroadCastReceiver class. In this class, we will create a onReceive() method with context and intent as parameter. This 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 getDisplayOriginatingAddress() gives us the sender number getMessageBody() gives us the message text.

Create a new Intent OTP and send it through LocalBroadcastManager.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.SmsMessage;

public class MySMSBroadCastReceiver extends BroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent)
    {
        // Get Bundle object contained in the SMS intent passed in
        Bundle bundle = intent.getExtras();
        SmsMessage[] smsm = null;
        String sms_str ="";

        if (bundle != null)
        {
            // Get the SMS message
            Object[] pdus = (Object[]) bundle.get("pdus");
            smsm = new SmsMessage[pdus.length];
            for (int i=0; i<smsm.length; i++){
                smsm[i] = SmsMessage.createFromPdu((byte[])pdus[i]);

                sms_str += "\r\nMessage: ";
                sms_str += smsm[i].getMessageBody().toString();
                sms_str+= "\r\n";

                String Sender = smsm[i].getOriginatingAddress();
                //Check here sender is yours
                Intent smsIntent = new Intent("otp");
                smsIntent.putExtra("message",sms_str);

                LocalBroadcastManager.getInstance(context).sendBroadcast(smsIntent);

            }
        }
    }
}

Add TextView in Layout

We will display message in Acitivity class when user get the OTP SMS, so we need to add TextView in the acivity_main.xml file.

 <TextView
        android:id="@+id/txtview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="5"
        android:singleLine="false"
        android:textSize="20sp"
        />



Register OTP Intent

Override OnResume() or OnPause() method to get receive OTP Intent while got the SMS.

@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);
}

Register BroadCastReceiver

Read OTP SMS in your current activity and display it via TextView. Add below code in Activity 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");

                TextView tv = (TextView) findViewById(R.id.txtview);
                tv.setText(message);
            }
        }
    };

Andoid GET OTP SMS

Final Acitivity Class


import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (checkAndRequestPermissions()) {
            // carry on the normal flow, as the case of  permissions  granted.
        }

    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase("otp")) {
                final String message = intent.getStringExtra("message");

                TextView tv = (TextView) findViewById(R.id.txtview);
                tv.setText(message);
            }
        }
    };

    private  boolean checkAndRequestPermissions() {
        int permissionSendMessage = ContextCompat.checkSelfPermission(this,
                Manifest.permission.SEND_SMS);
        int receiveSMS = ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS);
        int readSMS = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
        List<String> listPermissionsNeeded = new ArrayList<>();
        if (receiveSMS != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.RECEIVE_MMS);
        }
        if (readSMS != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_SMS);
        }
        if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.SEND_SMS);
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this,
                    listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
                    REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }

    @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);
    }
}



  • shalu bansal

    setContentView(R.layout.activity_main);
    R cannot be resolved.what s ths R?
    How to resolve ths error?

    • Re-build your project. Your project is not build properly. Check, have you activity_main.xml?

  • datta sonawane

    dud your app does not work