× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Android Message: How to send/receive SMS using the built-in messaging application in Android

This article is focused on the practicalities of sending and receiving text and data messages within the Android system.

Android offers full access to SMS functionality from our applications with the SMSManager. Basically by using the SMS Manager, we can replace the native SMS application or create new type of presentations that can send text messages, react to the received texts, or use SMS as a data transport layer. SMS message delivery is not always timely, so SMS is not really suitable for anything which requires real-time responsiveness.

Basically the widespread adoption of SMS networks make it particularly good tool for delivering content to non-Android users and reducing the dependency on the third-party servers. As a technology, SMS implements a mechanism that allows you to send text messages to other mobile phone users, irrespective of whether they have Android phones or not. SMS is supported by almost every phone on earth, so the latency is not an issue, and updates are infrequent, in such situation SMS data messages are an excellent process.

Sending SMS Messages:

Short Message Service messaging in Android is handled by the SmsManager. We can get a reference to the SMS Manager by using the static method SMSManger.getDefault, that type of protocol is shown below.

Listing 1: Creating SMS manager

SmsManager smsManager = SmsManager.getDefault();

Actually to send SMS messages our applications require the SEND_SMS permission. To request this permission, add it to the manifest file through a uses-permission tag that is shown below.

Listing 2: Setting permission

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

Sending Text Messages:

Our target is to send information in a text message format. Use sendTextMessage from the SMS Manager, passing in the address (phone number) of our recipient and the text message that we want to send, as shown in the snippet below:

Listing 3: Setting receiver and messages

String sendTo = “9231821234”;
String myMessage = “Android supports programmatic SMS messaging!”
smsManager.sendTextMessage(sendTo, null, myMessage, null, null);

Basically the final two parameters let you specify objectives of tracking the transmission and successful delivery of our messages or text. We will also discuss the broadcast receivers namespace and coding status in the next section.

Now here we will discuss the code that is generally built-in in our programming design when we want to send message to our nearest friends etc.

Listing 4: Sample showing message creating

   	protected void onCreate(Bundle savedInstanceState) 
      		sendBtn = (Button) findViewById(R.id.btnSendSMS);
      		txtphoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
      		txtMessage = (EditText) findViewById(R.id.editTextSMS);	
      		sendBtn.setOnClickListener(new View.OnClickListener() 
         			public void onClick(View view) 

The above method name is onCreate(Bundle savedInstanceState) and it is responsible for setting up the buttons, fields, textboxes etc for showing and storing the data. This sendSMSMessage(); method is used for generating the programming model of sending SMS as well as data.

Listing 5: Sample showing message sending

protected void sendSMSMessage() 
      		Log.info("Send SMS", "");
      		String phoneNo = txtphoneNo.getText().toString();
      		String message = txtMessage.getText().toString();
         			SmsManager smsManager = SmsManager.getDefault();
         			smsManager.sendTextMessage(phoneNo, null, message, null, null);
         			Toast.makeText(getApplicationContext(), "SMS sent.",
		catch (Exception e) 
         			Toast.makeText(getApplicationContext(),"SMS failed, please try again.",

The above method is used for sending messages from one system to another. This programming model is totally based on try catch block. By using the try catch block, SMS sent is written inside it for catching errors during execution.

Listing 6: Sample showing menu creation

   public boolean onCreateOptionsMenu(Menu menu) 
      // this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;

Basically when we create any SMS program, we also add menu items as per our requirement. Here onCreateOptionsMenu (Menu menu) method is used to generate our menu.

Shows the phone number and text messages option

Figure 1: Shows the phone number and text messages option

Shows that receiver accepts the text message.

Figure 2: Shows that receiver accepts the text message.

How to track and confirm SMS message delivery

It is one of the vital and important standard feature to track the transmission and delivery of our outgoing SMS messages, implement and register Broadcast Receivers that listen for the actions you specify and creating the Pending Intents you pass in to the sendTextMessage method.

The first Pending Intent parameter, sentIntent, is fired when the message is either successfully sent or fails to send. The result code for the Broadcast Receiver that receives this Intent will be one of the following:






It is to indicate a successful transmission.



It is to indicate a nonspecific failure



When the connection radio is turned off



To indicate a PDU failure

Table 1: Shows functions and their applications

The second Pending Intent parameter, deliveryIntent, is fired only after the destination recipient receives your SMS message.

The following code snippet shows a typical pattern for sending an SMS and monitoring the success of its transmission and delivery:

Listing 7: Sample showing broadcast receiver


// create the sentIntent parameter
Intent sentIntent = new Intent (SENT_SMS_ACTION);
Pending Intentsent = PendingIntent.getBroadcast (getApplicationContext (), 0, sentIntent, 0);

// create the delivery Intent parameter
Intent deliveryIntent = new Intent (DELIVERED_SMS_ACTION);
Pending Intentdeliver = PendingIntent.getBroadcast (getApplicationContext (), 0,deliveryIntent,0);

// Register the Broadcast Receivers
registerReceiver(new BroadcastReceiver() 
public void onReceive(Context _context, Intent _intent) {
switch (getResultCode())
case Activity.RESULT_OK:
[… send success actions … ]; 
[… generic failure actions … ]; 
[… Radio off failure actions …]; 
[… null PDU failure actions … ]; 
new IntentFilter(SENT_SMS_ACTION));
registerReceiver(new BroadcastReceiver()
public void onReceive(Context _context, Intent _intent)
[… SMS delivered actions … ]
new IntentFilter(DELIVERED_SMS_ACTION));
// Send the message
smsManager.sendTextMessage(sendTo, null, myMessage, sentPI, deliverPI);

The above code describes the broadcast receiver and its details. The first four lines create different types of intents like send intent and delivery intent etc. Next, the broadcast receiver is registered by using registerReceiver() method. The switch-case statement inside the receiver describes different types of messages. The transmission is monitored by using these messages inside onReceive() method.

Monitoring Outgoing SMS Messages:

It is an important procedure that Android debugging bridge supports sending SMS messages between multiple emulator instances. Now to send an SMS from one emulator to another, you need to specify the port number of the target emulator as the “to” address. Actually the android will automatically route our message to the target emulator instance, where it will be handled as a normal Short Message Services.

Sending Data Messages:

We can send the binary data via Short Message Services by using the sendDataMessage method on an SMS Manager. Actually the sendDataMessage method works much like sendTextMessage; nevertheless it includes additional parameters for the destination port and an array of the bytes that constitute the data which we want to send. The subsequent skeleton code confirms the basic structure of sending a data message system:

Listing 8: Sample showing data message sending

//Syntax are given here
Intent sentIntent = new Intent(SENT_SMS_ACTION);
PendingIntent sentPI = PendingIntent.getBroadcast(getApplicationContext(),0,sentIntent,0);
short destinationPort = 80;
byte[] data = [ … our data or information store here … ];
smsManager.sendDataMessage(sendTo, null, destinationPort, data, sentPI, null);

The above code describes the process for sending data messages. Intent and port is mentioned in the first three lines. In the 4th line the data is mentioned as an array of bytes. Then this data is sent along with the port number, intent etc.

Emergency Responder SMS Example:

Emergency Responder is also very important part for our SMS service process. Through this illustration, we will create an SMS application that turns an Android phone into an emergency response system. Once it is complete, we can set our phone to automatically respond to our friends and family members.

We will use location-based services to tell exactly where to find us. The robustness of the SMS network infrastructure makes SMS an excellent option for applications like this where reliability and accessibility are critical.

Process 1: Start by creating a new EmergencyResponder project that features an EmergencyResponder Activity.

  1. import android.app.Activity;
  2. import android.app.PendingIntent;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.content.IntentFilter;
  6. import android.content.BroadcastReceiver;
  7. import android.content.SharedPreferences;
  8. import android.location.Address;
  9. import android.location.Geocoder;
  10. import android.location.Location;
  11. import android.location.LocationManager;
  12. import android.os.Bundle;
  13. import android.telephony.gsm.SmsManager;
  14. import android.telephony.gsm.SmsMessage;
  15. import android.view.View;
  16. import android.view.View.OnClickListener;
  17. import android.widget.ArrayAdapter;
  18. import android.widget.Button;
  19. import android.widget.CheckBox;
  20. import android.widget.ListView;

All the twenty import files which are mentioned here are interrelated with one another.

The import android.app.Activity application is working to generate the activity set, the import android.content.BroadcastReceiver is used for the communication process, import android.location.Location is used for location detection, import android.telephony.gsm.SmsManager is used for communication with the telephone system, and import android.widget.ArrayAdapter is used for ArrayAdapter system processing.

Process 2:

public class EmergencyResponder extends Activity
//Add permissions for the finding our location as well as sending and receiving incoming //SMS messages to the project manifest.
<?xml version=”1.0” encoding=”utf-8”?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
<application android:icon=”@drawable/icon” android:label=”@string/app_name”>
<activity android:name=”.EmergencyResponder”android:label=”@string/app_name”>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
<uses-permission android:name=”android.permission.ACCESS_LOCATION”/>
<uses-permission android:name=”android.permission.SEND_SMS”/>

This above code is setting up for the emergency purpose message services.

Process 3:

This is modifying the main.xml layout resource. Include a List View to show the people requesting a status update and a series of buttons that users can press to send/response SMS messages. Use external resource references to fill in the button text; we will create them in the following section:

Process 4:

This is the step four which is used to finalize the SMS program.

<?xml version=”1.0” encoding=”utf-8”?>
android:text=”These people want to know if you’re ok”
android:text=”Include Location in Reply”/>
android:text=”Setup Auto Responder”/>

In the above program we are assigning some control points like labelRequestList, buttonLayout, checkboxSendLocation, okButton , notOkButton, autoResponder, myListView. These all are built-in here which controls the working of our SMS sending program blocks.

Actually we update the external strings.xml resource to include the program.zip file. We should also define the text message when distinguishing requests for status responses.

<?xml version=”1.0” encoding=”utf-8”?>
<string name=”app_name”>Emergency Responder</string>
<string name=”respondAllClearButtonText”> Yes I am fine don’t think about me. </string>
<string name=”respondRaniydayButtonText”>RANIYDAY! RANIYDAY! RANIYDAY!</string>
<string name=”respondAllClearText”> Yes I am fine don’t think about me!</string>
<string name=”respondRaniydayText”>Tell Esha I love her.</string>
<string name=”querystring”>Are you fine and Ok?</string>

This is the last step of the Graphical User Interface that we will complete.

In the modern mobile technology, SMS is very popular for sending information in a very fast way. SMS does not wait for the receiver, as it is not like receiving phone calls. You just need to send the text and rest will be handled by the system. So the flexibility of SMS makes it a very good friend of the modern technology. Android application is also very popular for different apps. One of the most important is SMS application.

Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login