How can I read SMS messages from the device programmatically in Android?


Introduction

Many times in android applications we get to see that the app reads sms from the users mobile device and displays that within the application. Such as when we are creating an sms application we display the sms from users mobile device within our application. In this article we will take a look on How can i read sms messages from the device programmatically in Android.

Implementation

We will be creating a simple application in which we will be creating a text view in which we will be displaying the heading of the application. After that we will be creating three more text views in which we will be displaying the sender name, message body as well as the date on which message has been received. In our application we will be displaying the recent message from the inbox which we have 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">

   <!-- text view to displaying heading of application -->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginTop="100dp"
       android:text="Read SMS in Android"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />

   <!-- on below line creating a text view for displaying the sms header -->
   <TextView
       android:id="@+id/idTVNumber"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVHeading"
       android:layout_centerHorizontal="true"
       android:layout_margin="10dp"
       android:padding="4dp"
       android:text="NUmber"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp" />

   <!-- on below line creating a text view for displaying the sms body -->
   <TextView
       android:id="@+id/idTVSMSBody"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVNumber"
       android:layout_centerHorizontal="true"
       android:layout_margin="10dp"
       android:padding="4dp"
       android:text="SMS Body"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp" />

   <!-- on below line creating a text view for displaying the date on which sms have recieved. -->
   <TextView
       android:id="@+id/idTVSMSDate"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVSMSBody"
       android:layout_centerHorizontal="true"
       android:layout_margin="10dp"
       android:padding="4dp"
       android:text="SMS Date"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp" />
</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 three more text views, in the first text view we are displaying the name of the sender, then in the second text view we are displaying the sms body of the sender and in the third text view we are displaying the date on which the message has been received.

Step 3: Adding permissions in AndroidManifest.xml file

Navigate to app>AndroidManifest.xml file and add below permissions to it in manifest tag to read sms.

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

Step 4: 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.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.IntentSender;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Telephony;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.credentials.Credential;
import com.google.android.gms.auth.api.credentials.CredentialPickerConfig;
import com.google.android.gms.auth.api.credentials.CredentialRequest;
import com.google.android.gms.auth.api.credentials.CredentialRequestResult;
import com.google.android.gms.auth.api.credentials.Credentials;
import com.google.android.gms.auth.api.credentials.CredentialsClient;
import com.google.android.gms.auth.api.credentials.CredentialsOptions;
import com.google.android.gms.auth.api.credentials.HintRequest;
import com.google.android.gms.auth.api.credentials.IdentityProviders;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

import org.w3c.dom.Text;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
   // creating variables for text view on below line for displaying sender name, body of the message and the date on which message is received.
   private TextView numberTV, bodyTV, dateTV;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       // initializing variables for text view on below line.
       numberTV = findViewById(R.id.idTVNumber);
       bodyTV = findViewById(R.id.idTVSMSBody);
       dateTV = findViewById(R.id.idTVSMSDate);
       // creating a variable for content resolver on below line.
       ContentResolver cr = getApplicationContext().getContentResolver();
       // creating a variable for cursor on below line and setting uri as sms uri.
       Cursor c = cr.query(Telephony.Sms.CONTENT_URI, null, null, null, null);
       // on below line checking if the cursor is not null.
       if (c != null) {
           // on below line moving to the first position.
           if (c.moveToFirst()) {
               // on below line extracting the sms data from the cursor.
               String smsDate = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.DATE));
               // on below line extracting the sender name/ number from cursor. .
               String number = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.ADDRESS));
               // on below line extracting the body of the sms from the cursor.
               String body = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.BODY));
               // on below line converting date in date format.
               Date dateFormat = new Date(Long.valueOf(smsDate));
               // on below line moving cursor to next position.
               c.moveToNext();
               // on below line setting data from the string to our text views.
               numberTV.setText("Sender is : " + number);
               bodyTV.setText("Body is : 
" + body); dateTV.setText(dateFormat.toString()); } // on below line closing the cursor. c.close(); } else { // on below line displaying toast message if there is no sms present in the device. Toast.makeText(this, "No message to show!", Toast.LENGTH_SHORT).show(); } } }

Explanation: In the above code firstly we are creating variables for text views. 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 the onCreate method we are initializing the button variable with the id which we have given in our activity_main.xml file. After that we are creating a variable for the content resolver. Then we are creating and initializing the variable for the cursor by passing the sms query and other params as null. After that we are checking if the cursor is not null. In that case we are moving the cursor to the first position. Inside this method we are extracting the different parts of an sms such as sender name, message body and the date on which the sms is received. After getting all the data we are setting this data to our text views which we have created. After that we close the cursor. If the cursor is null which means the inbox is empty, in that case we are displaying the toast message as no message to display.

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 read SMS messages from the device programmatically in Android.

Updated on: 08-May-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements