Home > Android API > Android API – SMS handling

Android API – SMS handling

December 29th, 2008

Many new application will use SMS as data delivery platform. Reality shows, on-demand movies etc request users to send predefined formatted SMS. Similarly some applications are coming up which sends data to user using SMS. Let’s see how such an application can be built using Android platform.

Android API support developing applications that can send and receive SMS messages. The android emulator does not support sending of the SMS currently. But the emulator can receive SMS. Lets explore the android SMS support and develop a small program that listens to the SMSes received on the device (on emulator) and will show that message as notification.

The event handling on Android is done with the help of intents and intent receivers. The intents  announce (or broadcast) the event and intent receivers respond to the event. Intent receivers act as the event handlers.

Let’s define an intent receiver that can handle the SMS received event:

package com.wissen.sms.receiver;
/**
* The class is called when SMS is received.
*/
public class SMSReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// TODO
}
}

We need to configure this intent receiver to receive SMS receive event. For SMS receive event android has defined an intent as ‘ android.provider.Telephony.SMS_RECEIVED ‘. The receiver can be configured in AndroidManifest.xml as follows:

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

To receive SMS, application also needs to specify permission for receiving SMS. The permission can be set in AndroidManifest.xml as follows:

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

Now our intent receiver is all set to be called when the android device will receive SMS. Now we only need to retrieve the received SMS and show the SMS text in a notification.

Here is the code of intent receiver that will read the SMS from intent received and show the first message (pdu).

public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();

		Object messages[] = (Object[]) bundle.get("pdus");
		SmsMessage smsMessage[] = new SmsMessage[messages.length];
		for (int n = 0; n &lt; messages.length; n++) {
		smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
		}

		// show first message
		Toast toast = Toast.makeText(context,
		"Received SMS: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
		toast.show();
		}

The SMS received by the Android device is in the form of pdus (protocol description unit). Class SmsMessage, defined in android.telephony.gsm package, can store information about the SMS. The class can also be used to create SmsMessage object from received pdus. Toast widget is used to show the SMS body as an notification.

Running the Program:
Only remaining thing now is running the application and sending the SMS message to the emulator. An SMS message can be sent to the emulator in the DDMS eclipse perspective (Dalvik Debug Monitor Service). ‘Emulator Control’ window can be used to send SMS message (an incoming number has to be provided which can be anything).

Here is the application screen shot in action,

Android SMS receiver application

Android SMS receiver application

Download the sample code here

Join the forum discussion on this post - (1) Posts

Android API , ,

  1. December 30th, 2008 at 03:28 | #1

    Nice post Prashant, very detailed.

  2. January 4th, 2009 at 08:04 | #2

    Thanks for a nice post.
    I tried the example and it worked for me without any problem.
    Keep the good work.

    Cheers,
    Vishwajeet

  3. admin
    January 4th, 2009 at 23:51 | #3

    Thanks Vishwajeet, glad it helped you.

  4. meryl
    January 28th, 2009 at 11:37 | #4

    Can you please tell me where I can find the source code for the above example? Thank you.

  5. admin
    February 2nd, 2009 at 01:58 | #5

    @meryl
    A link to the code is added in the post

  6. Jeremy
    February 12th, 2009 at 19:03 | #6

    Thanks for the post, it helped me out a ton! :)

  7. Kenny Yu
    March 11th, 2009 at 23:57 | #7

    How to intercept an SMS in terms of the SMS contents?
    1. The program is on top of SDK, no hacking!
    2. When an SMS is arriving at Android phone, the program should be able to erase the SMS in terms of the SMS contents;
    3. If an SMS is intercepted (erased), no database storage, no Inbox UI update
    4. Power cycle the Android phone, the SMS in-exists at all.

    Any API or design?

  8. admin
    March 12th, 2009 at 05:04 | #8

    Kenny, its definitely possible. Do get in touch with us on contact details if you are looking for solutions.

  9. Jeepston
    March 31st, 2009 at 09:02 | #9

    I guess not only Kenny is interested in this kind of functionality (intercepting SMS and accessing SMS db). So, could you be so kind and share your knowledge ob this topic? :)

  10. Adem
    April 16th, 2009 at 06:47 | #10

    Is it posssible to access to all messages. Not only new one.
    if it is possible how can we do that. which class which method?

  11. Stephen
    April 18th, 2009 at 20:12 | #11

    Hello Admin,
    I have error on “n < messages.length”, not sure why. Can you help me?

    package com.wissen.sms.receiver;

    import android.app.Activity;
    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 {
    /** Called when the activity is first created. */
    @Override
    public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();

    Object messages[] = (Object[]) bundle.get(“pdus”);
    SmsMessage smsMessage[] = new SmsMessage[messages.length];
    for (int n = 0; n < messages.length; n++) {
    smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
    }

    // show first message
    Toast toast = Toast.makeText(context,
    “Received SMS: ” + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
    toast.show();
    }
    }

  12. July 6th, 2009 at 13:26 | #12

    To listen to call state changes, I can use PhoneStateListener object and use TelephonyManage.listen() to start listening. Can I do similarly for SMS? Can you tell me the appropriate call for that?

  13. zeeshan
    July 16th, 2009 at 01:05 | #13

    @Codevalley
    Hi Codevalley,
    To listen to sms you can use BroadcastReceiver .
    First you can create a BroadcastReceiver as:
    public class SMSReceiver extends BroadcastReceiver {
    @Override

    public void onReceive(Context context, Intent intent) {

    getMessage();
    }

    private void getMessage() {

    if (intent.getAction().equals(ACTION)) {

    StringBuilder sb = new StringBuilder();

    Bundle bundle = intent.getExtras();

    if (bundle != null) {

    Object[] pdusObj = (Object[]) bundle.get(“pdus”);

    SmsMessage[] messages = new SmsMessage[pdusObj.length];

    for (int i = 0; i < pdusObj.length; i++) {

    messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);

    }

    Log.i(LOG_TAG, “[SMSApp Bundle] ” + bundle.toString());

    // Feed the StringBuilder with all Messages found.

    for (SmsMessage currentMessage : messages) {

    this.originator = currentMessage.getOriginatingAddress();

    this.message = currentMessage.getDisplayMessageBody();

    sb.append(“Received compressed SMS\nFrom: “);

    // Sender-Number

    sb.append(currentMessage.getDisplayOriginatingAddress());

    sb.append(“\n—-Message—-\n”);

    // Actual Message-Content

    sb.append(currentMessage.getDisplayMessageBody());

    }

    }

    }

    }

    }
    Now make an entry of this receiver in AndroidManifest.xml so that this receiver will be notified when a sms is received

  14. zeeshan
    July 16th, 2009 at 01:10 | #14
  15. kapnkore
    September 14th, 2009 at 01:55 | #15

    what if want to start an new activity after receivint the message or want to strore received sms on separate data base?how to startactivity from broadcast receivier class

  16. Hazhir
    November 27th, 2009 at 23:19 | #16

    can u explain more about

    Log.i(LOG_TAG, “[SMSApp Bundle] ” + bundle.toString());

    Thank you.

  17. Shyam
    November 28th, 2009 at 01:13 | #17

    @Hazhir
    hi Hazhir ,
    Log.i is just android’s logger. Its just like the System.out.println() which outputs to the display. You can see the output of the Log.i in the LogCat in the DDMS view. However an additional feature of this logger is that you can prefix it with a tag which can make it much easier to search for your comment. So the above statement will output the string “[SMSApp Bundle]” appended with the string description of ‘bundle’ under the LOG_TAG tag ( which happens to be a variable here, can hold any string value).

  18. VishnuR
    December 8th, 2009 at 02:34 | #18

    Is there any way to intercept outgoing or incoming SMSs or any way to block incoming or outgoing message.

    Currently working on Android2

  19. Shyam
    December 8th, 2009 at 04:40 | #19

    @VishnuR
    Hi Vishnu,
    The above code can be used to intercept incoming SMSes. However, you cannot as of yet block an incoming call/sms. You can however delete sms from inbox but only after the notification event is called; not on the fly.

  20. VishnuR
    December 8th, 2009 at 21:17 | #20

    @shyam..
    thnx shyam..i am new to android…any clu abt outgoing SMS.??.if i can’t block them…can i just catch a notification or something when a user send som message…(I am using the per-packaged messaging app of android 2)

    ok..wat about email and browser..can i block them….okay i know my qstns sound really really wierd..!!..but ..
    i am actually working on a project…to build a sheduler..which will block outgoing sms,email,browser and youtube for a particular time………

    anybody pls help….

  21. VishnuR
    December 8th, 2009 at 21:22 | #21

    one more thing…..if cant do the above things…just tell me if it is possible to hide or stop a prepackaged app of android(2.0) from the user for a particular period…[primary goal is to make dat service unavailable...]

  22. Shyam
    December 10th, 2009 at 04:19 | #22
  23. VishnuR
    December 11th, 2009 at 00:11 | #23

    @Shyam
    thanx shyam ,
    but it is all about setting permissions and enforcing security..i dont know how dat will help me ….. because i’ve already told dat i am new to this …….

    R8 now i generated a task list which lists out all the background(running) tasks and services….i know it is possible to start a particular activity from the list using intents…but is der a way to terminate or kill dat activity…???

    ..did looked everywer for a solution…but cant find any….

    also do u have any idea regarding “ActivityMonitor”..please dont refer me a link to the api documentation,coz it is only providing a minimal explanation.

    once again thank you for spentin ur time ….

  24. Shyam
    December 11th, 2009 at 02:01 | #24

    @Shyam
    Hi ,sorry for not being specific !!!

    But i just wanted to quote the security architecture from the page :
    “Security Architecture

    A central design point of the Android security architecture is that no application, by default, has permission to perform any operations that would adversely impact other applications, the operating system, or the user. This includes reading or writing the user’s private data (such as contacts or e-mails), reading or writing another application’s files, performing network access, keeping the device awake, etc.

    An application’s process is a secure sandbox. It can’t disrupt other applications, except by explicitly declaring the permissions it needs for additional capabilities not provided by the basic sandbox. ”

    I’m not so sure if you can stop a prepackaged app from the user….

  25. VishnuR
    December 11th, 2009 at 21:12 | #25

    @Shyam

    thanx…
    now the picture is more clear……

    did u ever notice …dat starting an activity causes an intent to be fired..which holds the necessary things to start dat activity…
    what if i could write a receiver..capture dat activities attention and “just close it”…….
    ..may be a stupid idea…but it feels like der is some way,to do dat..

    anyway thanks for your help dude…..

  26. VishnuR
    December 11th, 2009 at 21:14 | #26

    @Shyam
    …and if u hav any suggestions or ideas in ur mind(related to my prob)…please do post here…

  27. VishnuR
    December 13th, 2009 at 00:20 | #27

    anyone please help…….

  28. param
    December 25th, 2009 at 03:32 | #28

    I have the same problem as yours, we can’t block calls through code!?!
    If you find solution pls tell me…..

  29. December 27th, 2009 at 09:11 | #29

    very nice solution..
    I am also interested in block notification when sms received, if anyone knows how to do that, please share :)

    marko

  30. Shubham
    February 26th, 2010 at 22:38 | #30

    @admin
    Can u please show how cabn i delete msg b4 come into inbox
    pls do needful

    Thanx

  31. Shubham
    February 27th, 2010 at 00:28 | #31

    @VishnuR
    Hi Vishnu this is shubham here I am new here CAn u pls tel me hw i cn dele Last SMS from Inbox

    i del all the sms bt last one remain there

  32. Shubham
    February 27th, 2010 at 00:55 | #32

    N thnxs for reply
    bt req like My X(say) gfriend use my cell and i nevr want to allow to seee my Y gfriend SMS in my inbox sooo

  33. sadasivareddy
    March 1st, 2010 at 00:58 | #33

    Any API is supported for email sending and receving in android ,If it is know me please tell me.

  34. March 2nd, 2010 at 21:07 | #34

    I’m considering an android phone. Would it be possible to write an app that takes an incoming SMS and formats it into a URL string that then gets sent to a server.

    I teach HS. I want to ask my students a question in class, have them text me the answer and then be able to do item analysis/grading/display of answers. School will then be like american idol.

    The parsing of the URL into the database I can do.

  35. chethan
    March 22nd, 2010 at 07:25 | #35

    Hi
    I just wanted to know whether senddatamessage for a specific port is working in android 2.0 or 2.1.. if it works how and where do i register a specific port….i don have options to register a port in manifest…so please anyone help me out…

    Thanks in advance

  36. Sivambigai
    May 6th, 2010 at 04:49 | #36

    hi..

    When capturing the message, i m getting the following exception and my application pccomm getting closed.

    05-06 15:01:26.171: WARN/ActivityManager(78): Timeout of broadcast BroadcastRecord{44a310d0 android.provider.Telephony.SMS_RECEIVED} – receiver=android.os.BinderProxy@4487c7e8
    05-06 15:01:26.171: WARN/ActivityManager(78): Receiver during timeout: BroadcastFilter{44842d78 ReceiverList{4485dc30 7365 com.ami.pccomm/10050 remote:4487c7e8}}
    05-06 15:01:26.171: INFO/Process(78): Sending signal. PID: 7365 SIG: 9
    05-06 15:01:26.221: INFO/WindowManager(78): WIN DEATH: Window{448f4880 com.ami.pccomm/com.ami.client.smsredirector.SMSIntentReceiver paused=false}
    05-06 15:01:26.241: INFO/ActivityManager(78): Process com.ami.pccomm (pid 7365) has died.
    05-06 15:01:26.291: VERBOSE/Telephony(357): getOrCreateThreadId uri: content://mms-sms/threadID?recipient=%2B919095155574
    05-06 15:01:26.301: VERBOSE/Telephony(357): getOrCreateThreadId cursor cnt: 1
    05-06 15:01:26.991: WARN/AudioFlinger(52): write blocked for 203 msecs, 206 delayed writes, thread 0xd768

    if any one knows help me ..

    Thanks

  37. Shyam
    May 7th, 2010 at 01:01 | #37

    @Sivambigai
    hi Sivambigai,
    Make sure you made the necessary changes to the AndroidManifest.xml file, like adding the permissions , and registering your Receiver class. ( like ”

    ” )
    Also you can download the source code from the link provided above else from here: http://androidcompetencycenter.com/wp-content/uploads/SMSManager.zip .
    This code works for all versions of android. Else just copy the “Receiver” package from it and add the permissions and above code to your AndroidManifest.xml. ( Take a look at the given AndroidManifest.xml file for reference ) .

  38. Shyam
    May 7th, 2010 at 01:15 | #38

    @Sivambigai
    hi the blank line in the above comment just points out the receiver xml code given in the above post .

  39. slaman
    May 19th, 2010 at 23:06 | #39

    its doing well but sms notification still exists………..anybody know how to clear this sms notification…………
    i will be thank full

  40. Denzil Ferreira
    July 14th, 2010 at 16:59 | #40

    SMS handling is not only about checking received SMS, how about sent SMS, how do you capture that?

  41. Dwinx
    July 23rd, 2010 at 04:20 | #41

    Could someone please clear Chethan’s doubt about the sms port issue. Because I am also in that same situation. I need to send an sms to a specific app. in adroid.

  1. No trackbacks yet.