Android API – SMS handling
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 < 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
Download the sample code here
Nice post Prashant, very detailed.
Thanks for a nice post.
I tried the example and it worked for me without any problem.
Keep the good work.
Cheers,
Vishwajeet
Thanks Vishwajeet, glad it helped you.
Can you please tell me where I can find the source code for the above example? Thank you.
@meryl
A link to the code is added in the post
Thanks for the post, it helped me out a ton!
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?
Kenny, its definitely possible. Do get in touch with us on contact details if you are looking for solutions.
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?
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?
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();
}
}
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?
@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
@Codevalley
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
can u explain more about
Log.i(LOG_TAG, “[SMSApp Bundle] ” + bundle.toString());
Thank you.
@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).
Is there any way to intercept outgoing or incoming SMSs or any way to block incoming or outgoing message.
Currently working on Android2
@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.
@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….
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...]
@VishnuR
hey Vishnu
Take a look at
http://developer.android.com/guide/topics/security/security.html
cheers
@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 ….
@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….
@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…..
@Shyam
…and if u hav any suggestions or ideas in ur mind(related to my prob)…please do post here…
anyone please help…….
I have the same problem as yours, we can’t block calls through code!?!
If you find solution pls tell me…..
very nice solution..
I am also interested in block notification when sms received, if anyone knows how to do that, please share
marko
@admin
Can u please show how cabn i delete msg b4 come into inbox
pls do needful
Thanx
@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
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
Any API is supported for email sending and receving in android ,If it is know me please tell me.
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.
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
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
@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 ) .
@Sivambigai
hi the blank line in the above comment just points out the receiver xml code given in the above post .
its doing well but sms notification still exists………..anybody know how to clear this sms notification…………
i will be thank full
SMS handling is not only about checking received SMS, how about sent SMS, how do you capture that?
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.