Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Receiving an SMS Message in an Android Application

Author: Rachee Singh -- Published? true -- FormatLanguage: W

Problem:

Enabling your application to receive an SMS.

Solution:

Using a broadcast receiver to listen for incoming SMSs and then extracting the message from them.

Discussion:

When an Android device receives a message, a broadcast intent is fired (the intent also includes the SMS that is sent). The application can register to receive these intents. The intent has an action android.provider.Telephony.SMS_RECEIVED. The application designed to receive SMSs should include the RECEIVE_SMS permission in the manifest:


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

When a message is received, the onReceive method (overriden) is called. Within this method, the message can be processed. From the intent that is received, the sms message has to be extracted using the get() method. The BroadcastReceiver with the extracting the message part looks something like this:


public class invitationSMSreciever extends BroadcastReceiver {

	public void onReceive(Context context, Intent intent) {
		
		Bundle bundle = intent.getExtras();
		SmsMessage[] msgs = null;
		String message = "";
		if(bundle != null) {
			Object[] pdus = (Object[]) bundle.get("pdus");
			msgs = new SmsMessage[pdus.length];
			
			for(int i=0; i<msgs.length;i++) {
				msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				message = msgs[i].getMessageBody();
				Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
			}
					
		}
		
	}

}

The code makes a toast with the contents of the SMS sent.

To register the invitationSMSreciever class for receiving the SMSs, add the following code in the manifest:


<receiver android:name=".invitationSMSreciever"
	android:enabled="true">
		<intent-filter>
			<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
			<category android:name="android.intent.category.DEFAULT"/>
		</intent-filter>		  
</receiver>

Download:

The source code for this project can be downloaded from https://docs.google.com/leaf?id=0B_rESQKgad5LMjk0YjJiZTgtZGI5ZC00Mjk3LTk2MGUtMjhkOGYzNmFmYWMz&hl=en_US&authkey=CMWZvskL.
No records found.