Android receive sms programmatically

In this Android tip, I am going to show you how to receive SMS programmatically. To achieve this goal, first you need to declare receiver that matches the android.provider.Telephony.SMS_RECEIVED action in AndroidManifest.xml file of your working current project. Then in the onReceive() method of BroadcastReceiver, you can extract SMS message from a passed in intent object. The onReceive() method is fired when your phone received a SMS message. In the example below, the application is launched automatically when there is an incoming message. The message is displayed in a TextView.
Now to have an example application on receiving SMS programmatically, create a new Android project and name it as smsreceiver. In the activity_main.xml file of the project, you need to add one TextView to display the received SMS.


<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"

tools:context="com.example.smsreceiver.MainActivity" >

   <TextView
     android:id="@+id/txtview"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:maxLines="5"
     android:singleLine="false"
     android:textSize="20sp"
     />
</RelativeLayout>


Then in your AndroidManifest.xml file, you need to declare a broadcast receiver as shown below. The value of the name attribute of the receiver is SMSBReceiver which is a class that extends the BroadcastReceiver. By setting the max value to the priority attribute, it is make sure that this application has the highest priority to receive the SMS. The value must be an integer. Higher numbers have a higher priority. The default value is 0. The value must be greater than -1000 and less than 1000. You also need to specify permissions to receive and read SMS on an Android device.
<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.testing"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
     android:minSdkVersion="8"
     android:targetSdkVersion="21" />
   <!-- Permissions to receive and read SMS -->
   <uses-permission android:name="android.permission.RECEIVE_SMS"/>
   <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=".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>
     <!-- Declare SMS Broadcast receiver -->
     <receiver android:name=".SMSBReceiver" >
     <intent-filter android:priority="999" >
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
     </intent-filter>
</receiver>
   </application>

</manifest>



Here is the content of the SMSBReceiver class. In the onReceive() method, Java code is written to get the Bundle object from the passed in intent. Then the sender number and message are extracted. These data are put in another intent object to be sent to the MainActivity. This process will launch the application when there is an incoming message on your Android phone.

package com.example.testing;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;


public class SMSBReceiver extends BroadcastReceiver
{
  @Override
  public void onReceive(Context context, Intent intent)
  {
   // Get Bundle object contained in the SMS intent passed in
  Bundle bundle = intent.getExtras();
  SmsMessage[] smsm = null;
  String sms_str ="";
  if (bundle != null)
  {
    // Get the SMS message
    Object[] pdus = (Object[]) bundle.get("pdus");
    smsm = new SmsMessage[pdus.length];
    for (int i=0; i<smsm.length; i++){
   smsm[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
      sms_str += "Sent From: " + smsm[i].getOriginatingAddress();
      sms_str += "\r\nMessage: ";
      sms_str += smsm[i].getMessageBody().toString();
      sms_str+= "\r\n";
    }
    
   // Start Application's MainActivty activity
    Intent smsIntent=new Intent(context,MainActivity.class);
    smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    smsIntent.putExtra("sms_str", sms_str);
    context.startActivity(smsIntent);
  }
}
}


In the onCreate() method of the MainActivity class, you receive the data (sender number and message) sent from the broadcast and display it on the TextView.

protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     // Get intent object sent from the SMSBroadcastReceiver
     Intent sms_intent=getIntent();
     Bundle b=sms_intent.getExtras();
     TextView tv=(TextView)findViewById(R.id.txtview);
     if(b!=null){
     // Display SMS in the TextView    
     tv.setText(b.getString("sms_str"));
     }
    
   }

Android-receive-sms-programmatically

Posted by: Dara | post date: 10-27-2014 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.