Click here to Skip to main content
11,721,289 members (87,118 online)
Click here to Skip to main content

Tagged as

Sending SMS in Android and Receiving Feedback

, 11 Jul 2013 CPOL 48.2K 4.3K 33
Rate this:
Please Sign up or sign in to vote.
This article explains how to send SMS in Android and receive sent and delivered feedback.

Sample Image

Introduction

Using Android programming, you can integrate SMS capabilities into your own Android applications. This allows you to create Android applications which can send and receive SMS messages from your Android device. In this article I am explaining how you can send SMS messages programmatically. Also I am showing how you can monitor the status of the SMS message, for example, when the message is sent and when it is delivered to the receiver.

Here, I am assuming that the reader has a basic knowledge of creating Android apps using the Eclipse IDE.

Background

Android requires permissions needed by an application to be specified in the AndroidManifest.xml file. This ensures that when the application is installed, the user knows which permissions are required by it. Also it gives an option to the user to decide whether or not to install the SMS application because such an application requires a user to incur the cost of sending SMS messages.

Using the Code

The following line is required in the AndroidManifest.xml file to allow the application to send SMS messages:

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

The following is the full code of the AndroidManifest.xml file:

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

    <uses-permission android:name="android.permission.SEND_SMS"/>
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMSSenderActivity"
                  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>

The user interface of the SMS application consists of two EditText fields for accepting the message text and the phone number, respectively and a Button control to send the message. The following is the content of the main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<TextView android:text="Enter SMS Text: " android:id="@+id/textView1" 
  android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content" 
  android:id="@+id/editText1"></EditText>
<TextView android:text="Enter Phone Number: " android:id="@+id/textView2" 
  android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content" 
  android:id="@+id/editText2"></EditText>
<Button android:text="Send SMS" android:id="@+id/button1" android:layout_width="wrap_content" 
  android:layout_height="wrap_content"></Button>
</LinearLayout>

The SmsManager class is used to programmatically send an SMS message. This class is instantiated by using the static getDefault() method as follows:

SmsManager sms=SmsManager.getDefault();

The sendTextMessage() method of the SmsManager class is used to send a text message as follows:

sms.sendTextMessage(phone, null, message, piSent, piDelivered);

The sendTextMessage() method accepts five parameters, as follows:

  • phone - Recipient's phone number
  • address - Service Center Address (null for default)
  • message - SMS message to be sent
  • piSent - Pending intent to be invoked when the message is sent
  • piDelivered - Pending intent to be invoked when the message is delivered to the recipient

The pending intents piSent and piDelivered are created as follows before calling the sendTextMessage() method:

PendingIntent piSent=PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT"), 0);
PendingIntent piDelivered=PendingIntent.getBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0);

The PendingIntent object piSent is used to notify the sender that the message has been sent and the PendingIntent object piDelivered is used to notify the sender that the message has been delivered to the recipient when the recipient actually receives the message.

Note: The piDelivered PendingIntent does not fire in the Android emulator. You have to test the application on a real device to view it. However, the piSent PendingIntent works on both, the emulator as well as on a real device.

Two BroadcastReceiver objects, smsSentReceiver and smsDeliveredReceiver, are created in the onResume() method. These are registered using the registerReceiver() method as follows:

registerReceiver(smsSentReceiver, new IntentFilter("SMS_SENT"));
registerReceiver(smsDeliveredReceiver, new IntentFilter("SMS_DELIVERED"));

Inside each BroadcastReceiver object, the onReceive() method is overridden to check the result code using the getResultCode() method and display the appropriate message.

The two BroadcastReceiver objects are unregistered in the onPause() method as follows:

unregisterReceiver(smsSentReceiver);
unregisterReceiver(smsDeliveredReceiver);

Following is the full source code of the application:

package com.azim;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SMSSenderActivity extends Activity implements View.OnClickListener {
    /** Called when the activity is first created. */
    EditText txtMessage,txtPhone;
    Button btnSend;
    BroadcastReceiver smsSentReceiver, smsDeliveredReceiver;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txtMessage=(EditText)findViewById(R.id.editText1);
        txtPhone=(EditText)findViewById(R.id.editText2);
        btnSend=(Button)findViewById(R.id.button1);
        btnSend.setOnClickListener(this);
    }

    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        SmsManager sms=SmsManager.getDefault();
        String phone=txtPhone.getText().toString();
        String message=txtMessage.getText().toString();
        PendingIntent piSent=PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT"), 0);
        PendingIntent piDelivered=PendingIntent.getBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0);
        sms.sendTextMessage(phone, null, message, piSent, piDelivered);
    }
    
    public void onResume() {
        super.onResume();
        smsSentReceiver=new BroadcastReceiver() {
            
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                // TODO Auto-generated method stub
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS has been sent", Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic Failure", Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "No Service", Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio Off", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
                }
                
            }
        };
        smsDeliveredReceiver=new BroadcastReceiver() {
            
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                // TODO Auto-generated method stub
                switch(getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS Delivered", Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        };
        registerReceiver(smsSentReceiver, new IntentFilter("SMS_SENT"));
        registerReceiver(smsDeliveredReceiver, new IntentFilter("SMS_DELIVERED"));
    }
    
    public void onPause() {
        super.onPause();
        unregisterReceiver(smsSentReceiver);
        unregisterReceiver(smsDeliveredReceiver);
    }
}

Execute the application on the Android emulator. This will start the default AVD. Using the Android SDK and AVD Manager option, launch another AVD as follows:

On the first emulator (5554), type the message and number of the second emulator (5556) and click on the Send SMS button. This will show the message on the second emulator and the sent notification on the first emulator.

Points of Interest

The advantage of sending SMS programmatically is that you can send dynamically generated messages through your applications. Also you don't need a real device to test this feature. You can test the application on the emulator before transferring it to the real device.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Azim Zahir
Instructor / Trainer NIIT, India
India India
I am a trainer by profession. Currently I am working with NIIT (Mumbai, India) as a Senior Faculty. I enjoy programming as a hobby. My favorite technologies are Flash, Flex and Silverlight.

Of late I have developed keen interest in WPF and Windows Mobile programming.

Apart from computers, my favorite pastime is bicycling.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 2 Pin
Member 115926328-Apr-15 21:24
memberMember 115926328-Apr-15 21:24 
QuestionShort and Sweet. Pin
Jatin Kulkarni4-Jan-15 0:10
memberJatin Kulkarni4-Jan-15 0:10 
AnswerRe: Short and Sweet. Pin
Azim Zahir25-Apr-15 1:50
mvpAzim Zahir25-Apr-15 1:50 
Questiongr8 Tutorial Pin
anish.k abraham13-Dec-14 23:41
memberanish.k abraham13-Dec-14 23:41 
QuestionThank you. Pin
WuRunZhe19-Sep-14 20:19
memberWuRunZhe19-Sep-14 20:19 
AnswerRe: Thank you. Pin
Azim Zahir20-Sep-14 15:47
memberAzim Zahir20-Sep-14 15:47 
Answerthank you Pin
Solarin8115-Jul-14 12:31
memberSolarin8115-Jul-14 12:31 
GeneralRe: thank you Pin
Azim Zahir20-Sep-14 15:47
memberAzim Zahir20-Sep-14 15:47 
QuestionCan you write an article on how to receive SMS messages? Pin
Member 1089098717-Jun-14 13:38
memberMember 1089098717-Jun-14 13:38 
AnswerRe: Can you write an article on how to receive SMS messages? Pin
Azim Zahir23-Jun-14 21:55
memberAzim Zahir23-Jun-14 21:55 
QuestionMove from activity to fragment and get error. Pin
mat_rapit14-Feb-14 2:55
membermat_rapit14-Feb-14 2:55 
AnswerRe: Move from activity to fragment and get error. Pin
Azim Zahir23-Jun-14 21:53
memberAzim Zahir23-Jun-14 21:53 
Question"Enter Phone Number" to default Pin
mat_rapit13-Feb-14 15:52
membermat_rapit13-Feb-14 15:52 
AnswerRe: "Enter Phone Number" to default Pin
Azim Zahir23-Jun-14 22:11
memberAzim Zahir23-Jun-14 22:11 
QuestionGood tut... Pin
Aravinth A31-Dec-13 1:00
memberAravinth A31-Dec-13 1:00 
AnswerRe: Good tut... Pin
Azim Zahir3-Jan-14 16:11
memberAzim Zahir3-Jan-14 16:11 
Questionnor working Pin
Member 1042540025-Nov-13 21:35
memberMember 1042540025-Nov-13 21:35 
AnswerRe: nor working Pin
Azim Zahir27-Nov-13 0:25
memberAzim Zahir27-Nov-13 0:25 
Questionno receiver Pin
azmat ahmed8-Oct-13 9:40
memberazmat ahmed8-Oct-13 9:40 
QuestionGood One!! Vote 5 Pin
boss prabu20-Aug-13 17:18
memberboss prabu20-Aug-13 17:18 
AnswerRe: Good One!! Vote 5 Pin
Azim Zahir27-Aug-13 5:18
memberAzim Zahir27-Aug-13 5:18 
GeneralMy vote of 5 Pin
David H. Wright19-Aug-13 3:13
professionalDavid H. Wright19-Aug-13 3:13 
GeneralRe: My vote of 5 Pin
Azim Zahir19-Aug-13 16:42
memberAzim Zahir19-Aug-13 16:42 
QuestionProblem with intent Pin
Member 33345069-Aug-13 11:31
memberMember 33345069-Aug-13 11:31 
AnswerRe: Problem with intent Pin
Azim Zahir10-Aug-13 6:47
memberAzim Zahir10-Aug-13 6:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150901.1 | Last Updated 11 Jul 2013
Article Copyright 2013 by Azim Zahir
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid