How to listen for incoming SMS messages in Android?


Introduction

Many times in android applications we can see that OTP received for user authentication is detected automatically and it is added within the application automatically. Users don't have to add the otp manually. This can be done in android applications with the help of broadcast receivers. In this article we will take a look on How to listen for incoming sms messages in android application

Implementation

We will be creating a simple application in which we will be displaying two text views. First text view is for displaying the heading of our application. Second text view we will be creating for displaying the SMS which is being received. Now let's move towards android studio for creating a new project.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 2 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <!--     creating a text view on below line-->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:layout_marginStart="20dp"
       android:layout_marginTop="20dp"
       android:layout_marginEnd="20dp"
       android:layout_marginBottom="20dp"
       android:padding="4dp"
       android:text="Listen Incoming SMS Message in Android"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />
   <!--     creating a text view on below line-->
   <TextView
       android:id="@+id/idTVMessage"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVHeading"
       android:layout_centerInParent="true"
       android:layout_marginStart="20dp"
       android:layout_marginTop="20dp"
       android:layout_marginEnd="20dp"
       android:layout_marginBottom="20dp"
       android:padding="4dp"
       android:text="Message will appear here"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />
</RelativeLayout>

Explanation : In the above code we are creating a root layout as a Relative Layout. Inside this layout we are creating a text view which is used to display the heading of our application. After that we are creating a one more text view in which we will be displaying the SMS which we will be displaying the incoming sms received.

Step 3 : Creating an interface class

Navigate to app>java>your app’s package name>Right click on it>New Interface class and name it as MessageListnerInterface and add below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;
public interface MessageListenerInterface {
   // creating an interface method for messages received.
   void messageReceived(String message);
}

Explanation : In the above code we are creating a method which we will be using to set the received message within our application.

Step 4 : Creating one more class for Broadcast receiver

Navigate to app>java>your app’s package name>Right click on it>New Java class and name it as MessageBroadcastReciever and add below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class MessageBroadcastReceiver extends BroadcastReceiver {
   // creating a variable for a message listener interface on below line.
   private static MessageListenerInterface mListener;
   @Override
   public void onReceive(Context context, Intent intent) {
       // getting bundle data on below line from intent.
       Bundle data = intent.getExtras();
       // creating an object on below line.
       Object[] pdus = (Object[]) data.get("pdus");
       // running for loop to read the sms on below line.
       for (int i = 0; i < pdus.length; i++) {
           // getting sms message on below line.
           SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
           // extracting the sms from sms message and setting it to string on below line.
           String message = "Sender : " + smsMessage.getDisplayOriginatingAddress()
                   + "
Message: " + smsMessage.getMessageBody(); // adding the message to listener on below line. mListener.messageReceived(message); } } // on below line we are binding the listener. public static void bindListener(MessageListenerInterface listener) { mListener = listener; } }

Explanation : In the above code we are extending our class with Broadcast receiver which will listen to the incoming sms in android device. On message received it will be then displayed in our on message receive method. From there we can read our sms and use it within our application.

Step 5 : Working with AndroidManifest.xml file

Navigate to app>AndroidManifest.xml file and add below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools">
   <!-- adding permissions on below line -->
   <uses-permission android:name="android.permission.RECEIVE_SMS" />
   <uses-permission android:name="android.permission.READ_SMS" />
   <application
       android:allowBackup="true"
       android:dataExtractionRules="@xml/data_extraction_rules"
       android:fullBackupContent="@xml/backup_rules"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:roundIcon="@mipmap/ic_launcher_round"
       android:supportsRtl="true"
       android:theme="@style/Theme.JavaTestApplication"
       android:usesCleartextTraffic="true"
       tools:targetApi="31">
       <activity
           android:name=".MainActivity"
           android:exported="true">
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
           <meta-data
               android:name="android.app.lib_name"
               android:value="" />
       </activity>
       <!-- adding a broad cast receiver for message on below line -->
       <receiver
           android:name=".MessageBroadcastReceiver"
           android:exported="true">
           <!-- adding intent filter as sms received -->
           <intent-filter>
               <action android:name="android.provider.Telephony.SMS_RECEIVED" />
           </intent-filter>
       </receiver>
   </application>

</manifest>

Explanation : In the above code for AndroidManifest.xml file we are adding permissions to read sms. Along with that we are creating a receiver in which we are specifying the name of the receiver and adding action to it as sms received to receive the sms within our application.

Step 6 : Working with MainActivity.java file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements MessageListenerInterface {
   // creating variables on below line for text view.
   private TextView msgTV;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       // initializing variables on below line.
       msgTV = findViewById(R.id.idTVMessage);
       // adding bind listener for message receiver on below line.
       MessageBroadcastReceiver.bindListener(this);
   }
   @Override
   public void messageReceived(String message) {
       // setting message in our text view on below line.
       msgTV.setText(message);
   }
}

Explanation : In the above code firstly we are creating variables for our text view. Now we will get to see the onCreate method. This is the default method of every android application. This method is called when the application view is created. Inside this method we are setting the content view i.e the layout file named activity_main.xml to set the UI from that file. Inside this onCreate method we are initializing the variable for the text view with the id which we have given in our activity_main.xml file. After that we are adding a bind listener for our message broadcast receiver class. Along with that we are implementing our MainActivity file with MessageListnerInterface. Inside the messageRecieved method we are setting the message received to our text view to be displayed within our application.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note : Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above article we have taken a look on How to listen for an incoming SMS messages within an android application.

Updated on: 08-May-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements