How to detect when mobile phone received the SMS Message on Android.

Published by Igor Khrupin on

To receive SMS messages you need to create BroadcastReceiver for it.

Below you can download source code of sample Android project

Here is SmsBroadcastReceiver.java

package com.hrupin.sample.sms;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class SmsBroadcastReceiver extends BroadcastReceiver {

    private static final String TAG = SmsBroadcastReceiver.class.getSimpleName();
    public static final String SMS_CONTENT = "sms_content";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "Intent recieved: " + intent.getAction());

        Cursor c = context.getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
        c.moveToFirst();
        String smsBody = c.getString(12);
        Toast.makeText(context, "SMS RECEIVED:", Toast.LENGTH_LONG).show();
        Toast.makeText(context, smsBody, Toast.LENGTH_LONG).show();

        Intent fireActivityIntent = new Intent(context, SMSDetectorActivity.class);
        fireActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        fireActivityIntent.putExtra(SMS_CONTENT, smsBody);
        context.startActivity(fireActivityIntent);

    }
}

Also you need specific permissions:

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

Next step is put BroadcastReceiver into AndroidManifest

<application android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name">
    ..................
    <receiver android:name=".SmsBroadcastReceiver">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED">
            </action>
        </intent-filter>
    </receiver>
</application>

Here you can download source code of this sample Android project

Download it from github

1 Comment

www.jordans11concords.com · 18 August, 2012 at 15:47

Very valuable information, I am very grateful,I agree with your Blog and I will be back to check it more in the future~~~ so please keep up your work.

Leave a Reply

Avatar placeholder

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.