Send and Receive SMS Application from Android

Following code demonstrates how to send and receive SMS using Telephony API in Android

SendSMS.java

package com.example.sendreceivesms;

import java.util.ArrayList;

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.gsm.SmsManager;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends Activity {
	private static String SENT = "SMS_SENT";
	private static String DELIVERED = "SMS_DELIVERED";
	private static int MAX_SMS_MESSAGE_LENGTH = 160;
	static Context mContext;
	BroadcastReceiver smsSentReceiver, smsDeliveredReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = getApplicationContext();
		Button b = (Button)findViewById(R.id.button1);
		b.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// TODO Auto-generated method stub
				sendSMS("5554","HELLO from mca5b");
//				sendSMS("5554", "helloasdfadsklfjadslkfjadsklfjladskjflkadsjflksadjfkldsajflkadsjfkladsjflkadsjflkadsjflkasdjflkadsjflkadsjf" +
//						"SADKFJADSKLFJADSKLJFLADSKJFL;ADSKJFLADSKJFLKADSJFLKADSJFL;ADSKJFLKADS" +
//						"KASLDFJAKLDSJFKLADSJFLKASDJFLKADSJFLKADSJLKFJADSKLFJADSLKFADSJFLKASD" +
//						"LKADSJFLADKSJFDKLASJFL;AKSDJFLKADSJFL;KASDJFLKADSJFLKDSAJFLASDJFAS;DL" +
//						"AKLDSJFLADKSJFLKADSJFKLASDJFKLADSJFKLADSJFLKADJSLKFJASDKLFJASD" +
//						"ADSKLFJADSKLJFKALSDJFLKAJDSLKFJDASLKFJADLSKFJADSLFJASDL;KF" +
//						"adlskfjadlskfjal;dskfjalkdsjfl;kadsjfaldskjfaldskjflkdasjfl");
			}
		});
	}

	// ---sends an SMS message to another device---
	public void sendSMS(String phoneNumber, String message) 
	{
		//PendingIntent.get
		PendingIntent piSent=PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT"), 0);
		PendingIntent piDelivered=PendingIntent.getBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0);
		//		PendingIntent piSent = PendingIntent.getBroadcast(mContext, 0, new Intent(SENT), 0);
		//	PendingIntent piDel-ivered = PendingIntent.getBroadcast(mContext, 0,new Intent(DELIVERED), 0);
		SmsManager smsManager = SmsManager.getDefault();

		int length = message.length();          
		if(length > MAX_SMS_MESSAGE_LENGTH) {
			ArrayList<String> messagelist = 
					smsManager.divideMessage(message);     
			//	smsManager.sendMultipartTextMessage(phoneNumber, null, messagelist, piSent,piDelivered );
			smsManager.sendMultipartTextMessage(phoneNumber, null, messagelist,null,null); 

		}
		else
		{
			smsManager.sendTextMessage(phoneNumber, 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);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

SMSReciever.java

package com.example.sendreceivesms;

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

public class SMSReceiver extends BroadcastReceiver 
{
	@Override
	public void onReceive(Context context, Intent intent) 
	{
		//---get the SMS message passed in---
		Bundle bundle = intent.getExtras();        
		SmsMessage[] msgs = null;
		String str = "";            
		if (bundle != null)
		{
			//---retrieve the SMS message received---
			Object[] pdus = (Object[]) intent.getExtras().get("pdus");
			msgs = new SmsMessage[pdus.length];            
			for (int i=0; i<msgs.length; i++)
			 {
				msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
				str += "SMS from " + msgs[i].getOriginatingAddress();                     
				str += " :";
				str += msgs[i].getMessageBody().toString();
				str += "\n";        
			}
			//---display the new SMS message---
			Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
		}                         
	}

}

Manifest file

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.sendreceivesms.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>
        <receiver android:name=".SMSReceiver"> 
            <intent-filter> 
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" /> 
            </intent-filter> 
        </receiver>
 
    </application>

</manifest>
Advertisements

One thought on “Send and Receive SMS Application from Android

  1. Here i am providing you code for Save Message in Sent Items:

    /* To save in Sent items */
    ContentValues values = new ContentValues();
    values.put(“address”, phoneNumber);
    values.put(“body”, message);
    context.getContentResolver().insert(Uri.parse(“content://sms/sent”), values);

    Happy Coding 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s