Receiving SMS in Android

In this tutorial we'll create an Android application to receive SMS using BroadcastReceiver. On receiving the SMS we'll show a toast message and update TextView with incoming sms number and message body.

Adding Permission and BroadcastReceiver to AndroidManifest

We need to do couple of things:

Add permission to receive SMS
<uses-permission android:name="android.permission.RECEIVE_SMS"/>

Add BroadcastReceiver with an intent-filter to receiving SMS.
<receiver android:name="com.sushil.tech.readingsms.SmsReceiver">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
    </intent-filter>
</receiver>

Source Code:

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sushil.tech.readingsms" >

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="com.sushil.tech.readingsms.SmsReceiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>

    </application>

</manifest>

activity_sms.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvHeader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Received SMS"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/tvSmsBody"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tvHeader"
        android:layout_marginTop="16dp"
        android:scrollbars="vertical"/>

</RelativeLayout>

SMSActivity.java
package com.sushil.tech.readingsms;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.widget.TextView;

public class SMSActivity extends AppCompatActivity {

    TextView tvSmsBody;
    String fullSmsInfo = "";
    public static SMSActivity inst;

    public static SMSActivity instance() {
        return inst;
    }

    @Override
    public void onStart() {
        super.onStart();
        inst = this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);
        tvSmsBody = (TextView) findViewById(R.id.tvSmsBody);
        tvSmsBody.setMovementMethod(new ScrollingMovementMethod());
    }

    public void displaySms(String smsBody) {
        fullSmsInfo += smsBody + "\n\n";
        tvSmsBody.setText(fullSmsInfo);
    }
}

SmsReceiver.java
package com.sushil.tech.readingsms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver {

    Context mContext;
    @Override
    public void onReceive(Context context, Intent intent) {
        final Bundle bundle = intent.getExtras();
        try{
            if(bundle != null) {
                Object[] object = (Object[]) bundle.get("pdus");
                for(int i = 0; i < object.length; i++) {
                    SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) object[i]);
                    String phoneNumber = smsMessage.getDisplayOriginatingAddress();
                    String message = smsMessage.getDisplayMessageBody();
                    Log.i("SMS ", "from: " + phoneNumber + " " + message);
                    Toast.makeText(context, phoneNumber+": "+message, Toast.LENGTH_SHORT).show();

                    // Calling SMSActivity method to display using TextView
                    String fullSmsInfo = "From: "+phoneNumber+"\n"+message;
                    SMSActivity instance = SMSActivity.instance();
                    instance.displaySms(fullSmsInfo);
                }
            }
        } catch (Exception e){
            Toast.makeText(context, "Exception"+e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }
}

Test your SMS Application using Android Emulator

  • Rum Android Device Monitor by simply clicking on it from toolbar or go to Tools -> Android -> Android Device Monitor.
  • In Android Device Monitor now select DDMS and choose Emulator Control Tab.
  • Now you can enter Incoming number, select SMS option, enter message and click on send to receive SMS.
Test SMS Application in Android
Test SMS Application in Android

Note: Genymotion Emulator doesn't provide provide SMS Receiving feature in free version, so either you can go for full version or use Android Emulator as described above.

Screen Preview

Receiving SMS in Android
Receiving SMS in Android
SHARE

0 comments:

Post a Comment