How to read SMS in Android

In this tutorial we are going to show you how to read SMS messages under Android. Here is a simple program that displays a list of SMS messages stored on the device.

Android read SMS sample application

Android read SMS sample application

When an list element is clicked a SMS message body text is being displayed as a Toast message.

Here is the application code.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itcuties.android.apps"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
       android:minSdkVersion="8"
       android:targetSdkVersion="16" />
   
    <uses-permission android:name="android.permission.READ_SMS"/>

    <application
       android:allowBackup="true"
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >
       <activity
           android:name="com.itcuties.android.apps.MainActivity"
           android:label="@string/app_name" >
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
    </application>

</manifest>

You need to add a permission that allows your application to read SMS database. You need to add the permission to your application.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#000">
     
    <TextView
       android:id="@+id/smsNumberText"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="NUMBER_GOES_HERE">
    </TextView>
   
</LinearLayout>

Our application displays SMS senders numbers in a list. This layout represents single ListView row layout.

SMSData.java

package com.itcuties.android.apps.data;

/**
* This class represents SMS.
*
* @author itcuties
*
*/
public class SMSData {

   // Number from witch the sms was send
   private String number;
   // SMS text body
   private String body;
   
   public String getNumber() {
       return number;
   }
   
   public void setNumber(String number) {
       this.number = number;
   }
   
   public String getBody() {
       return body;
   }
   
   public void setBody(String body) {
       this.body = body;
   }
   
}

This class represents SMS data. Our application uses only SMS sender number and the message body text.

ListAdapter.java

package com.itcuties.android.apps;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.itcuties.android.apps.data.SMSData;


/**
* List adapter for storing SMS data
*
* @author itcuties
*
*/
public class ListAdapter extends ArrayAdapter<SMSData> {

   // List context
    private final Context context;
    // List values
    private final List<SMSData> smsList;
   
   public ListAdapter(Context context, List<SMSData> smsList) {
       super(context, R.layout.activity_main, smsList);
       this.context = context;
       this.smsList = smsList;
   }

   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
       LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       
       View rowView = inflater.inflate(R.layout.activity_main, parent, false);
        
       TextView senderNumber = (TextView) rowView.findViewById(R.id.smsNumberText);
       senderNumber.setText(smsList.get(position).getNumber());
        
       return rowView;
   }
   
}

This is our list adapter implementation. This class is responsible for building list rows. In the getView method a single ListView’s row is being constructed.

MainActivity.java

package com.itcuties.android.apps;

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

import android.app.ListActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.itcuties.android.apps.data.SMSData;

/**
* Main Activity. Displays a list of numbers.
*
* @author itcuties
*
*/
public class MainActivity extends ListActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       List<SMSData> smsList = new ArrayList<SMSData>();
       
       Uri uri = Uri.parse("content://sms/inbox");
       Cursor c= getContentResolver().query(uri, null, null ,null,null);
       startManagingCursor(c);
       
       // Read the sms data and store it in the list
       if(c.moveToFirst()) {
           for(int i=0; i < c.getCount(); i++) {
               SMSData sms = new SMSData();
               sms.setBody(c.getString(c.getColumnIndexOrThrow("body")).toString());
               sms.setNumber(c.getString(c.getColumnIndexOrThrow("address")).toString());
               smsList.add(sms);
               
               c.moveToNext();
           }
       }
       c.close();
       
       // Set smsList in the ListAdapter
       setListAdapter(new ListAdapter(this, smsList));
       
   }

   @Override
   protected void onListItemClick(ListView l, View v, int position, long id) {
       SMSData sms = (SMSData)getListAdapter().getItem(position);
       
       Toast.makeText(getApplicationContext(), sms.getBody(), Toast.LENGTH_LONG).show();
       
   }
   
}

This class constructs a list of the SMS senders numbers. It extends a ListActivity. In the onCreate method of this class SMS database is being read. Results are stored in the list adapter. The main code that lets Android read SMS messages is this fragment.

Android read SMS code

Uri uri = Uri.parse("content://sms/inbox");
Cursor c= getContentResolver().query(uri, null, null ,null,null);
startManagingCursor(c);
       
if(c.moveToFirst()) {
	for(int i=0; i < c.getCount(); i++) {
		// Do something here for example read the body
		String body = c.getString(c.getColumnIndexOrThrow("body")).toString();
		
		c.moveToNext();
	}
}
c.close();

As you can see we are connecting to the content database, the SMS inbox and query it for the SMS messages.

Download this sample code here.

This code is available on our GitHub repository as well.

9 Responses to "How to read SMS in Android"

  1. Raam says:

    Doesn’t work on Samsung s2, S3, Grand phones…? I don’t see anything related to address and body when using these phones?
    Do you have a fix for that?

    Reply
  2. Said says:

    Thanks for the tutorial! It works!

    What would be the code to display sms sender’s name from contacts list instead of just a number?

    Reply
    • itcuties says:

      Hello Said,
      You need to query contact database for contact’s display name. Try this code where PHONE_NUMBER_HERE is a phone number of a contact you want to get the display name for.

      Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(PHONE_NUMBER_HERE));
      Cursor c = context.getContentResolver().query(lookupUri, new String[]{ContactsContract.Data.DISPLAY_NAME},null,null,null);
      try {
      	c.moveToFirst();
          String displayName = c.getString(0);
      	
      } catch (Exception e) {
      	// Do something with the exception like logging it or so.
      }finally{
      	c.close();
      }
      

      You will need the permission to read the contacts database.

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

      Cheers,
      itcuties

      Reply
  3. chris says:

    Thank you for your tutorial Mam.. I’ll try for my new project using Sms

    Reply
  4. rgreso says:

    Hi,
    I want to get body of SMS when I click on one. I have tried an approach simmilar to contact picker. Here is my code :

    public class Decrypt extends Fragment {
    Button loadButton;
    EditText smsDisplay;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.decrypt, null);
       // Button loadButton=(Button)v.findViewById(R.id.)
        loadButton=(Button)v.findViewById(R.id.buttonLoad);
        smsDisplay=(EditText)v.findViewById(R.id.editTextLoad);
        loadButton.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View v) {
    
                Intent sendIntent = new Intent(Intent.ACTION_VIEW);         
                sendIntent.setData(Uri.parse("sms:"));
                //sendIntent.setType(Sm)
                //sendIntent.putExtra("sms_body",""); 
    
                startActivityForResult(sendIntent,2);
            }
        });
    
    
        return v;
    
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try{
        // if (resultCode == Activity.RESULT_OK) {
        Uri ur = data.getData();
        Cursor c = getActivity().getContentResolver().query(ur, null, null,
                null, null);
        if (c.moveToFirst()) {
            String s = c
                    .getString(c
                            .getColumnIndex("body"));
            System.out.println(s);
            Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
            smsDisplay.setText(s);
    }
        }catch(Exception e){
            e.printStackTrace();
        }
        // }
    }
    }
    

    It opens a Inbox like when I open original sms app in anroid, but when I click on one message it doesnt copy body of that sms in my edittext. Please couul you look at my code and find mistake?

    Thanks a lot for your time

    Reply
  5. hitesh says:

    HELLO, I WANT A BACKUP AND RESTORE OF ALL MESSAGES LIKE INBOX, DRAFT ETC.

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Java by Example App is available at Google Play Store NOW