Show me the code! – By Davanum Srinivas

December 15, 2007

Android – Listen for incoming SMS messages

Filed under: Uncategorized — Davanum Srinivas @ 10:06 am

Get the latest m3-rc37a version of android

Here’s a screen shot

1

Setup the Android Manifest with the permission and the Intent Receiver

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.apache.sms">
    <uses-permission id="android.permission.RECEIVE_SMS" />
    <application>
        <receiver class="SMSApp">
            <intent-filter>
                <action android:value="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
    </application>
</manifest> 

Code a simple Intent Listener

package org.apache.sms;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentReceiver;
import android.os.Bundle;
import android.provider.Telephony;
import android.util.Log;
import android.telephony.gsm.SmsMessage;

public class SMSApp extends IntentReceiver {
    private static final String LOG_TAG = "SMSApp";

    /* package */ static final String ACTION =
            "android.provider.Telephony.SMS_RECEIVED";

    public void onReceiveIntent(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION)) {
            StringBuilder buf = new StringBuilder();
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
                for (int i = 0; i &lt; messages.length; i++) {
                    SmsMessage message = messages[i];
                    buf.append("Received SMS from  ");
                    buf.append(message.getDisplayOriginatingAddress());
                    buf.append(" - ");
                    buf.append(message.getDisplayMessageBody());
                }
            }
            Log.i(LOG_TAG, "[SMSApp] onReceiveIntent: " + buf);
            NotificationManager nm = (NotificationManager) context.getSystemService(
                    Context.NOTIFICATION_SERVICE);

            nm.notifyWithText(123, buf.toString(),
                    NotificationManager.LENGTH_LONG, null);

        }
    }

    private void appendData(StringBuilder buf, String key, String value) {
        buf.append(", ");
        buf.append(key);
        buf.append('=');
        buf.append(value);
    }
}

Running the sample



  • Install the APK using “adb install SMSApp.apk” as usual

  • Open a telnet session to localhost at port 5554 and type “sms send +5085551212 hello” to simulate an sms message
  • Download Source and APK from here – SMSApp.zip

47 Comments »

  1. Dims – you need full text Atom feeds! ๐Ÿ™‚

    Comment by Dan Diephouse — December 15, 2007 @ 3:01 pm

  2. good job, D.

    Comment by andrewxuheng — December 20, 2007 @ 1:32 pm

  3. Very useful and good written tutorial. Thank you!

    Comment by Russian Translit — January 10, 2008 @ 8:57 pm

  4. Hi, davanum nice tutorial…. i tried it and it sun successfully….however I was wondering if sending the sms as part of an activity is possible or not ? I was trying to use something called SMSManager , but couldn’t test it.Would be greatful if you could suggest something.
    thanks in avance:]

    Comment by csagar — January 13, 2008 @ 8:53 am

  5. Keep up the good work. I need all the help I need and youttutorial have gone a long way to close the gaps. Thanks ๐Ÿ™‚

    Comment by Joseph Dung — February 12, 2008 @ 7:57 am

  6. Hi,
    This is cool. But I thought that the emulator should be listening to any incoming SMSs by default. Its fucntionality that should be provided in the phone.

    Anyway, this is a good example.

    Comment by Dexter — February 19, 2008 @ 2:31 pm

  7. Hi this is bhavan am just tried to use your SMSApp application but i got this error at line
    nm.notifyWithText(123, buf.toString(),
    NotificationManager.LENGTH_LONG, null);
    NotificationManager.LENGTH_LONG cannot be resolved
    could you please suggest how to solve this error to my mail id.And is this application work to send an sms from emulator?

    Comment by Bhavana — March 20, 2008 @ 4:02 am

  8. i’ve the same error ๐Ÿ˜

    NotificationManager.LENGTH_LONG cannot be resolved

    Comment by shitfull — March 28, 2008 @ 1:01 pm

  9. You can use Toast.maketext() replace Notification manager

    Comment by RoSippA — May 6, 2008 @ 3:03 am

  10. Hello,
    Use

    import android.widget.Toast; // import

    Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
    instead of NotificationManager.

    Comment by Rifat Shahriyar — May 9, 2008 @ 4:55 am

    • Hi My Dear,
      Here I have imported this package but I have a doubt about the first argument(context) of makeText method. Here which type of value we can pass?
      Thanks in advance………
      Regards,
      Ravisankara
      +91 988 477 9432

      Comment by Ravisankara — August 13, 2009 @ 9:39 am

      • do you really think he is going to call India to tell you which type of value you can pass?

        Comment by Ejder Yurdakul — March 7, 2010 @ 1:26 pm

  11. sorry buf.toString() instead of sb.toString()

    Comment by Rifat Shahriyar — May 9, 2008 @ 4:57 am

  12. .i’m using m5-rc15 and have used android.widget.Toast as Rafit says w/o error. But I’m having a problem deploying: when i try “adb install “, 0 bytes install – “110 KB/s (0 bytes in 3520.000s)”. In Eclipse, I’m not sure how to setup the prj so that it builds and runs in the emulator (theres no activity in this prj)..
    Thoughts?

    Comment by ben — June 6, 2008 @ 9:42 pm

  13. This does not work anymmore..

    Comment by sylvester steele — July 2, 2008 @ 6:49 am

  14. Hey Davanum,

    where is SMSApp.apk. this zip file cannot be founded..

    Comment by janaarth — August 18, 2008 @ 5:03 am

  15. Hi Davanum,

    Greetings to u.

    I’m newer to Android.

    I’m trying to get depth knowledge in Intent, IntentReceiver, Service..

    I’ve tried ur sample application. I got error in the part “Code a simple Intent Listener” as “The import android.provider.Telephony cannot be resolved”.

    Can u please help me as soon as possible… ๐Ÿ˜ฆ

    Thanks in advance.

    Comment by Yasmin — October 17, 2008 @ 2:24 am

  16. the class IntentReceiver does no longer exists in the SDK 1.1 and is renamed to BroadcastReceiver.

    hope this helps running this nice example.

    Comment by guido — February 22, 2009 @ 3:39 pm

  17. Hi,everyone..
    I have a problem to this code..
    I have an error on
    import android.provider.Telephony;

    the import cannot be risolved..
    Why?

    Comment by DoM — March 16, 2009 @ 5:30 am

  18. DoM:

    It appears this package is only available in the Open Source version and not available in 1.1 SDK.

    Comment by MV — March 18, 2009 @ 10:34 pm

  19. Nice tutorial

    Did somebody updated this tutorial to 1.1 SDK.

    Also the books available are not updated.

    Comment by JHandal — March 25, 2009 @ 9:14 pm

  20. Can any one tell me how i can Remove Incoming SMS b4 come into inbox..

    pls do needful
    Thanx

    Comment by shubham — February 27, 2010 @ 12:02 am

  21. ACt i m able to delete msg via inboxx where stil last sms remain

    Comment by shubham — February 27, 2010 @ 12:07 am

  22. Hi,
    Can my application receive SMS when its not running?

    My requirement is:
    1.My application is in dead state.
    2.My device receives a SMS.
    3.My application while in dead state, receives it. If its in some particular format eg with some prefix eg: ‘MyAppName’:xyz, my application will read the SMS and will call API to start itself do processing as per commands in SMS text.
    4. Basically I am trying to do application wake up by any means.
    THanks
    Sam

    Comment by sam — March 18, 2010 @ 12:58 am

    • I have similar need, Sam. My application may be triggered to run by an SMS message with contents of a particular format; or when the app is already running an incoming SMS may trigger an action within the app.

      It seems to me that there may need to be a service always running, without a UI, to always receive the SMS arrival intents, and that that in turn would start the activity in the application which initializes the UI, or begins the app’s response within an existing UI.

      However, my app is only interested in those SMSs that are directed to the app; all others should be handled by the default SMS app; and any SMSs that my app handles should be invisible to the user, i.e. should not appear in the SMS inbox — whether the app causes them to be deleted from the inbox or can intercept them before they reach the inbox.

      I’ve seen examples of how to set yourself up to receive incoming SMS notifications, but nothing that gives a hint as to how to accomplish the rest. Worse, I recall having read something somewhere that said that there is no SMS content provider exposed. Which could mean that what I want to do is impossible. Which would be a nice thing to find out sooner than later…

      Comment by Paul — March 24, 2010 @ 12:43 pm

      • Hi Paul,
        Did this App Directed SMS problem resolved? I tried deleting the SMS from Inbox but I get exceptions.

        thanks
        Sam

        Comment by sam — April 26, 2010 @ 8:31 am

      • hi Sam n Paul
        I’m also searching for the same thing for past 2 days. I’d got how to send and receive sms and to invoke an activity upon receiving an sms, but is invoked for any sms and that’s not my need..
        If u’d got any thread on this please share it, i may be grateful to you.
        regards…

        Comment by Shinas — May 18, 2012 @ 11:45 pm

    • Not yet. I haven’t followed up on it. This task has been assigned to another member of our team. She believes it can be done but as far as I know hasn’t actually tried yet.

      Comment by Paul — April 29, 2010 @ 7:39 am

  23. Hi to everyone

    Plz tell me anyone how to send sms to another pc using android

    I am new to android…..

    Comment by pradeep — July 29, 2010 @ 5:14 am

  24. Hi Every1,

    can any1 help by giving me code to delete SMSs before they reach the inbox…and trap the senders phone number….

    Plz…its urgent..

    Thanx in anticipation

    Comment by medma — October 6, 2010 @ 5:31 am

  25. any code to store “sent SMS” in a file? or just get notification of an outgoing SMS???

    Comment by Bill Adam — October 18, 2010 @ 2:11 am

  26. Hello ,

    Can you please attach the zip file again, its not accessible now.

    Comment by Ramesh — August 25, 2011 @ 4:13 am

  27. thanks man very useful tutorial

    Comment by ajeet — August 29, 2011 @ 4:04 am

  28. awesome

    Comment by wysiwyg — September 15, 2011 @ 4:41 am

  29. Please Attached Zip File Again.

    Comment by Dipak Keshariya — September 15, 2011 @ 7:26 am

  30. I m not able to download zip. It gives page not found error. Actually i have to know to register this BroadcastReciever from activity. I tried but not able to listen incoming message. Please Help.

    Comment by Ekta — September 16, 2011 @ 2:19 am

    • the link for the SmSApp.zip is broken,

      Comment by Tralala — November 8, 2011 @ 6:57 pm

  31. it very useful but added u’l give a graphical layout for android beginners ……….thanks

    Comment by J Balaji — January 5, 2012 @ 12:19 am

  32. Sorry
    I have generate this class….. but “Intent Receiver and Telephony” does not support….”””””The import android.content.IntentReceiver cannot be resolved”””””” This error was occured.
    Wt ll i do……

    Pls give me suggestion…

    Comment by Muthu — January 27, 2012 @ 7:51 am

  33. guys please i need some help my project is based on smsapp anyone can just give his/her email address mine its mbuzwa@gmail.com

    Comment by Mkhululi Khustarico Buzwa — May 2, 2012 @ 1:27 pm

  34. nice one!but i always expect a screenshot of the output too

    Comment by ayushman — July 10, 2012 @ 2:16 am

  35. I cant Download the Source, can someone send by email to me? Thnks!
    robsonpca@gmail.com

    Comment by Robson — August 23, 2012 @ 9:39 am

  36. please attach the zip file again or please send through mail

    Comment by Sharon — May 6, 2013 @ 11:39 pm

  37. Please Attached Zip File Again.

    Comment by aykt — December 22, 2013 @ 8:33 am

  38. how to detect a specific number on incoming sms?? please help me

    Comment by dns — July 21, 2014 @ 2:57 am

  39. hey i want to do this but in a other app, i can do this thing

    Comment by david — October 31, 2014 @ 3:34 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.