SMS Sender Example In Android

This example shows how you can send/receive SMS through your application.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it SMSSenderExample.

2.) Write following into main.xml:

 

<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="6dip">
<CheckBox
android:id="@+id/sms_enable_receiver"
android:text="@string/sms_enable_receiver"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableLayout
android:padding="6dip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">

<Button
android:id="@+id/sms_send_message"
android:text="@string/sms_send_message"
android:layout_column="1" />

<TextView
android:id="@+id/sms_status"
android:layout_column="1" />

 

 

3.) Create and write following into src/SmsMessageReceiver.java:

 

package com.example.smssenderexample;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsMessage;

public class SmsMessageReceiver extends BroadcastReceiver {
private static final String TAG = "SmsMessageReceiver";

@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras == null)
return;

Object[] pdus = (Object[]) extras.get("pdus");

for (int i = 0; i < pdus.length; i++) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]);
String fromAddress = message.getOriginatingAddress();
String fromDisplayName = fromAddress;

Uri uri;
String[] projection;

uri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(fromAddress));
projection = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME };

// Query the filter URI
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst())
fromDisplayName = cursor.getString(0);

cursor.close();
}

Intent di = new Intent();
di.setClass(context, SmsReceivedDialog.class);
di.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
di.putExtra(SmsReceivedDialog.SMS_FROM_ADDRESS_EXTRA, fromAddress);
di.putExtra(SmsReceivedDialog.SMS_FROM_DISPLAY_NAME_EXTRA, fromDisplayName);
di.putExtra(SmsReceivedDialog.SMS_MESSAGE_EXTRA, message.getMessageBody().toString());
context.startActivity(di);
break;
}
}
}

 

 

4.) Create and write following into src/SmsReceivedDialog.java:

 

package com.example.smssenderexample;

import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;

public class SmsReceivedDialog extends Activity implements OnInitListener {
private static final String TAG = "SmsReceivedDialog";

private static final int DIALOG_SHOW_MESSAGE = 1;

public static final String SMS_FROM_ADDRESS_EXTRA = "com.example.android.apis.os.SMS_FROM_ADDRESS";
public static final String SMS_FROM_DISPLAY_NAME_EXTRA = "com.example.android.apis.os.SMS_FROM_DISPLAY_NAME";
public static final String SMS_MESSAGE_EXTRA = "com.example.android.apis.os.SMS_MESSAGE";

private TextToSpeech mTts;

private String mFromDisplayName;
private String mFromAddress;
private String mMessage;
private String mFullBodyString;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

mFromAddress = getIntent().getExtras().getString(SMS_FROM_ADDRESS_EXTRA);
mFromDisplayName = getIntent().getExtras().getString(SMS_FROM_DISPLAY_NAME_EXTRA);
mMessage = getIntent().getExtras().getString(SMS_MESSAGE_EXTRA);

mFullBodyString = String.format(
getResources().getString(R.string.sms_speak_string_format),
mFromDisplayName,
mMessage);

showDialog(DIALOG_SHOW_MESSAGE);
mTts = new TextToSpeech(this, this);
}

public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e(TAG, "TTS language is not available.");
} else {
mTts.speak(mFullBodyString, TextToSpeech.QUEUE_ADD, null);
}
} else {
// Initialization failed.
Log.e(TAG, "Could not initialize TTS.");
}
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_SHOW_MESSAGE:
return new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_email)
.setTitle("Message Received")
.setMessage(mFullBodyString)
.setPositiveButton(R.string.reply, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Begin creating the reply with the SmsMessagingDemo activity
Intent i = new Intent();
i.setClass(SmsReceivedDialog.this, SMSSenderExample.class);
i.putExtra(SMSSenderExample.SMS_RECIPIENT_EXTRA, mFromAddress);
startActivity(i);

dialog.dismiss();
finish();
}
})
.setNegativeButton(R.string.dismiss, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
finish();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
finish();
}
}).create();
}
return null;
}
}

 

 

5.) Write following into res/values/strings.xml:

 

SMSSenderExample
Hello world!
Settings
SMSSenderExample
Enable SMS broadcast receiver
Recipient #
Message Body
Send
Message from "%1$s": %2$s
Reply
Dismiss

Share

 

6.) Add following 2 permissions into your manifest file:


7.) Run for output.

Steps:

1.) Create a project named SMSSenderExample and set the information as stated in the image.

Build Target: Android 4.0
Application Name: SMSSenderExample
Package Name: com. example. SMSSenderExample
Activity Name: SMSSenderExample
Min SDK Version: 8

2.) Open SMSSenderExample.java file and write following code there:

 

package com.example.smssenderexample;

import java.util.List;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SMSSenderExample extends Activity {
/** Tag string for our debug logs */
private static final String TAG = "SmsMessagingDemo";

public static final String SMS_RECIPIENT_EXTRA = "com.example.android.apis.os.SMS_RECIPIENT";

public static final String ACTION_SMS_SENT = "com.example.android.apis.os.SMS_SENT_ACTION";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

if (getIntent().hasExtra(SMS_RECIPIENT_EXTRA)) {
((TextView) findViewById(R.id.sms_recipient)).setText(getIntent().getExtras()
.getString(SMS_RECIPIENT_EXTRA));
((TextView) findViewById(R.id.sms_content)).requestFocus();
}

// Enable or disable the broadcast receiver depending on the checked
// state of the checkbox.
CheckBox enableCheckBox = (CheckBox) findViewById(R.id.sms_enable_receiver);

final PackageManager pm = this.getPackageManager();
final ComponentName componentName = new ComponentName("com.example.android.apis",
"com.example.android.apis.os.SmsMessageReceiver");

enableCheckBox.setChecked(pm.getComponentEnabledSetting(componentName) ==
PackageManager.COMPONENT_ENABLED_STATE_ENABLED);

enableCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG, (isChecked ? "Enabling" : "Disabling") + " SMS receiver");

pm.setComponentEnabledSetting(componentName,
isChecked ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
});

final EditText recipientTextEdit = (EditText) SMSSenderExample.this
.findViewById(R.id.sms_recipient);
final EditText contentTextEdit = (EditText) SMSSenderExample.this
.findViewById(R.id.sms_content);
final TextView statusView = (TextView) SMSSenderExample.this.findViewById(R.id.sms_status);

// Watch for send button clicks and send text messages.
Button sendButton = (Button) findViewById(R.id.sms_send_message);
sendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (TextUtils.isEmpty(recipientTextEdit.getText())) {
Toast.makeText(SMSSenderExample.this, "Please enter a message recipient.",
Toast.LENGTH_SHORT).show();
return;
}

if (TextUtils.isEmpty(contentTextEdit.getText())) {
Toast.makeText(SMSSenderExample.this, "Please enter a message body.",
Toast.LENGTH_SHORT).show();
return;
}

recipientTextEdit.setEnabled(false);
contentTextEdit.setEnabled(false);

SmsManager sms = SmsManager.getDefault();

List messages = sms.divideMessage(contentTextEdit.getText().toString());

String recipient = recipientTextEdit.getText().toString();
for (String message : messages) {
sms.sendTextMessage(recipient, null, message, PendingIntent.getBroadcast(
SMSSenderExample.this, 0, new Intent(ACTION_SMS_SENT), 0), null);
}
}
});

// Register broadcast receivers for SMS sent and delivered intents
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = null;
boolean error = true;
switch (getResultCode()) {
case Activity.RESULT_OK:
message = "Message sent!";
error = false;
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
message = "Error.";
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
message = "Error: No service.";
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
message = "Error: Null PDU.";
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
message = "Error: Radio off.";
break;
}

recipientTextEdit.setEnabled(true);
contentTextEdit.setEnabled(true);
contentTextEdit.setText("");

statusView.setText(message);
statusView.setTextColor(error ? Color.RED : Color.GREEN);
}
}, new IntentFilter(ACTION_SMS_SENT));
}
}

 

 

3.) Compile and build the project.

Output

Leave a Comment:

12 comments
arunkarthi says November 1, 2012

sir, whether the SMS sender programming is working but im not received any sms

Reply
Richard Warner says December 7, 2012

Cannot figure out why you have two sets of instructions, (7) algorithm and then (3) steps? Is not all the code needed in one project? Are there two projects here?

I tried doing the (3) steps as an Eclipse project, but it claims this line is deprecated:
import android.telephony.gsm.SmsManager;

Am new to Eclipse and Android and do not know yet how to go about finding the replacement for that import.

Reply
Quoc Truong says December 7, 2012

Dear Sir:

The code is not running to the Android 4.1. Could you please update the code to the new Android SDK?

Thanks,
Quoc Truong

Reply
Sunil Dangi says December 24, 2012

Hi, its showing error on the Project Folder,not in individual files……….any reason….plz explain………

Reply
Everton Gonçalves says April 26, 2013

Hello,
Enjoyed the post and would like to know if would make available the source code of the example. Would be useful.

Thank you.

Reply
deepa says May 2, 2013

nice..

Reply
lamy says June 3, 2013

Hi ;

I tried to change the sendersms code wit a default mobile number and with a default message text for an automatic send but it does not work

is there a way to send automatic messages by SMS

thank you

Reply
lamy says June 3, 2013

I would like to do one button send automatic SMS messages

Reply
Meghna says June 18, 2013

Thanks for the nice and good looking example, thanks… Even this http://www.compiletimeerror.com/2013/06/send-sms-in-android-example.html might help you out… Have a look…

Reply
isha says July 28, 2013

sir
can you please help me in retrieving sms details of a month like number at which sms is sent,date of sms,no. of sms sent,type of sms(local,std).Sir i’m new to android and don’t know much coding and i have to submit my app please help me sir.
Thank you.

Reply
Mayaa says August 21, 2013

Thanks for the clean example man!! Even this http://www.compiletimeerror.com/2013/06/send-sms-in-android-example.html was good, have a look.. May help..

Reply
vijaya says September 12, 2013

It showing message like message sent! but iam not received any message

Reply
Add Your Reply