Android Read Sms Example

Android allows to read it sms using  built-in SMS Content Provider. With the help of Content Provider we can read the sms already exist in your phone and we display it in our application.Suppose if we want to read the newly incoming messages also ,we need a SmsBroadcastReciever class which will receive the incoming messages.

Note

Refer How to verify otp automatically in android which will explain how to read newly incoming messages in android.In this tutorial we will learn how to read sms in android which already inside the messenger app using SMS Content Provider. Let us start by creating a new project in Android studio.

1.Creating New Project

  1. Create a new project in Android Studio from File -> New Project
  2. Fill the required fields like Application name and package name and click Next
  3.  Select Basic activity and click Next, and click  Finish Button.A default activity will be created as MainActivity.java with layouts activity_main.xml and content_main.xml

2. Here is the code for your activity_main.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    android:fitsSystemWindows="true"
    tools:context="ratingbar.example.com.inbox.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

2. Place the below code in content.xml file which will be located in res->layout. In this tutorial we will read sms and will display in a listview . So we will have a listview widget in the following code.

Refer Android listview and Android custom listview with images if your are not familiar in implementing listview.

<?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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="ratingbar.example.com.inbox.MainActivity"
    tools:showIn="@layout/activity_main">

    <ListView
        android:id="@+id/lv_sms"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></ListView>

</RelativeLayout>

Since we need to display the items in a list we need to configure a listview also for that:

3. Create a class SmsModel.java under java/your package/

SmsModel.java

package ratingbar.example.com.inbox;

/**
 * Created by Ramees on 8/19/2016.
 */
public class SmsModel {

    String mobile,message;

    public SmsModel(String mobile, String message) {
        this.mobile = mobile;
        this.message = message;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

4. Next step is to create an adapter class  for listview and layout for list item. First create a layout under res/layout

layout_sms_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_mobile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="bold" />


    <TextView
        android:id="@+id/tv_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:textSize="16sp" />

</LinearLayout>

5. Create Adapter class under java/your package/

SmsAdapter.java

package ratingbar.example.com.inbox;

/**
 * Created by Ramees on 8/19/2016.
 */
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;


public class SmsAdapter extends BaseAdapter{

    ArrayList<SmsModel> smsModelArrayList;
    Context context;
    private static LayoutInflater inflater=null;;

    public SmsAdapter(MainActivity mainActivity, ArrayList<SmsModel> smsModelArrayList) {
// TODO Auto-generated constructor stub

        context=mainActivity;
        this.smsModelArrayList = smsModelArrayList;
        inflater = ( LayoutInflater )context.
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
// TODO Auto-generated method stub
        return smsModelArrayList.size();
    }

    @Override
    public Object getItem(int position) {
// TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
// TODO Auto-generated method stub
        return position;
    }

    public class Holder
    {
        TextView tv_mobile;
        TextView tv_message;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
        Holder holder=new Holder();
        View view;
        SmsModel item = smsModelArrayList.get(position);
        view = inflater.inflate(R.layout.layout_sms_item, null);

        holder.tv_mobile = (TextView) view.findViewById(R.id.tv_mobile);
        holder.tv_message = (TextView) view.findViewById(R.id.tv_message);

        holder.tv_mobile.setText(item.getMobile());
        holder.tv_message.setText(item.getMessage());

        return view;
    }

}

6.Here is the code for MainActivity.java which contains the code for reading and displaying all sms

package ratingbar.example.com.inbox;

import android.app.ProgressDialog;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    ListView lv_sms;
    ArrayList<SmsModel> smsModelArrayList;
    SmsAdapter smsAdapter;
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //method for initialisation
        init();

        //Method to read sms and load into listview
        readSms();
    }

    private void init() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading sms");

        smsModelArrayList = new ArrayList<>();
        lv_sms = (ListView) findViewById(R.id.lv_sms);
        smsAdapter = new SmsAdapter(MainActivity.this,smsModelArrayList);
        lv_sms.setAdapter(smsAdapter);

    }

    public void readSms(){

        Uri uri = Uri.parse("content://sms/inbox");
        Cursor c = getContentResolver().query(uri, null, null ,null,null);
        startManagingCursor(c);

        progressDialog.show();
        // Read the sms data
        if(c.moveToFirst()) {
            for(int i = 0; i < c.getCount(); i++) {

                String mobile = c.getString(c.getColumnIndexOrThrow("address")).toString();
                String message = c.getString(c.getColumnIndexOrThrow("body")).toString();

                //adding item to array list
                smsModelArrayList.add(new SmsModel(mobile, message));
                c.moveToNext();
            }

        }
        c.close();

        progressDialog.dismiss();
        // notifying listview adapter

        smsAdapter.notifyDataSetChanged();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

7. Finally you need to add the below permission in your AndroidManifest.xml

Note : You need to give the permission explicitly inside code if you are using target version greater than 22.

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

If you are not familiar with requesting permission in run time ,please refer
How to request persmission dynamically in android

output

android_sms
android_sms

It is possible to read sms automatically and use in other application.In Many of the new application there is a facility to automatically read sms and verify otp automatically. The below link will explain how to verify otp automatically in android.

How to read sms and verify otp automatically 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.

Add a Comment

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