andbook!.pdf - Learning Android Get an anddev.org - Android-Shirt Back to index
anddev.org Header Logo
FAQ Search Top rated articles Browse Feeds anddev.org - Authors Contact Details Register Log in

Recognize/React on incoming SMS

Goto page 1, 2, 3, 4, 5  Next
 
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials
Author Message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2439
Location: College Park, MD

PostPosted: Sun Dec 16, 2007 11:24 pm    Post subject: Recognize/React on incoming SMS Reply with quote

This Tutorial was inspired by the nice, but almost uncommented davanum Apache Blog.
Recognize/React on incoming SMS

What you will learn: You will learn how to recognize/react on incoming SMS by using a IntentReceiver. A possible scenario is, to play a music when there is an incoming SMS or modify the SMS.

Idea Designed/Tested with sdk-version: m5-rc14

Question Problems/Questions: Write it right below...

Difficulty: 2 of 5 Smile

What it will look like:
Think away the 'compressed' as this screenshot is from my sms-compression app Smile
Screenshot was taken with sdk-version m3 (m5 looks similar)


Description:
0.)What we want to do is to react on the Intent "android.provider.Telephony.SMS_RECEIVED", which is fired by the System when there is an Incoming SMS. This will be done by an 'passive' IntentReceiver. This IntentReceiver will show a Notification (like in the picture above) and start a Main-Activity afterwards.

Note that we require a permission in the AndroidManufest.xml to receive the incoming sms:
XML:
<uses-permission android:name="android.permission.RECEIVE_SMS" />

This is the full AndroidManufest.xml:
XML:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.anddev.android.smsexample">

    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <application android:icon="@drawable/icon">
        <!-- The Main Activity that gets started by the IntentReceiver listed below -->
        <activity android:name=".SMSActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- This class will react on the SMS show a notification
                        and start the Main-App afterwards -->

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


1.)So we now need to implement the IntentReceiver we call "SMSReceiver" and the MainActivity we call "SMSActivity".

Lets workout the "SMSReceiver" first:
The uninteresting parts first:
Java:
package org.anddev.android.smsexample;

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.telephony.gsm.SmsMessage;
import android.util.Log;

public class SMSReceiver extends IntentReceiver {
     /** TAG used for Debug-Logging */
     private static final String LOG_TAG = "SMSReceiver";

     /** The Action fired by the Android-System when a SMS was received.
      * We are using the Default Package-Visibility */

     private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";


Idea This is the method, that is called when the IntentReceiver is 'invoked' by the System. This just happens, becuase we exposed this Class in the AndroidManifest.xml Idea

Java:
     // @Override
     public void onReceiveIntent(Context context, Intent intent) {
          if (intent.getAction().equals(ACTION)) {
               // if(message starts with SMStretcher recognize BYTE)
               StringBuilder sb = new StringBuilder();
               
               /* The SMS-Messages are 'hiding' within the extras of the Intent. */
               Bundle bundle = intent.getExtras();
               if (bundle != null) {
                    /* Get all messages contained in the Intent*/
                    SmsMessage[] messages =
                         Telephony.Sms.Intents.getMessagesFromIntent(intent);
                    
                    /* Feed the StringBuilder with all Messages found. */
                    for (SmsMessage currentMessage : messages){
                         sb.append("Received compressed SMS\nFrom: ");
                         /* Sender-Number */
                         sb.append(currentMessage.getDisplayOriginatingAddress());
                         sb.append("\n----Message----\n");
                         /* Actual Message-Content */
                         sb.append(currentMessage.getDisplayMessageBody());
                    }
               }
               /* Logger Debug-Output */
               Log.i(LOG_TAG, "[SMSApp] onReceiveIntent: " + sb);

               /* Show the Notification containing the Message. */
               Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();

Finally we start the Main-Activity doing the following:
Java:
               /* Start the Main-Activity */
               Intent i = new Intent(context, SMSActivity.class);
               i.setLaunchFlags(Intent.NEW_TASK_LAUNCH);
               context.startActivity(i);
          }
     }
}

2.) The SMSActivity can be everything that comes to your mind, like a little MusicPlayer, a SMS-Storage-App, a... EVERYTHING you can imagine Smile
Im using this code for the SMS-Compression-App i'll publicize when its ready Wink

Smile So thats it. I hope I could help you. Smile


Regards,
plusminus

_________________
Please remember, that this board is give & take Smile

| Android Development Community / Tutorials


Last edited by plusminus on Fri Oct 03, 2008 8:11 pm; edited 6 times in total
Back to top
View user's profile Send private message Send e-mail Visit poster's website
kadair
Junior Developer
Junior Developer


Joined: 16 Dec 2007
Posts: 16
Location: Cincinnati OH, United States

PostPosted: Mon Dec 17, 2007 1:02 am    Post subject: Reply with quote

This is exactly what I was looking for--it works great!

Thanks again,
Ken

_________________
"Your imagination is your preview of life's coming attractions." - Einstein

http://www.AppSocial.com


Last edited by kadair on Tue Dec 18, 2007 5:44 pm; edited 1 time in total
Back to top
View user's profile Send private message Visit poster's website
tum0rc0re
Senior Developer
Senior Developer


Joined: 25 Nov 2007
Posts: 102
Location: Moscow, Russia

PostPosted: Mon Dec 17, 2007 6:48 am    Post subject: Reply with quote

Thanks, buddy Smile It's excellent tutorial Smile
Back to top
View user's profile Send private message Visit poster's website MSN Messenger
Lex
Developer
Developer


Joined: 16 Nov 2007
Posts: 30

PostPosted: Mon Dec 17, 2007 10:16 pm    Post subject: Reply with quote

Thank you ! Keep up the good work !
Back to top
View user's profile Send private message
venkat
Senior Developer
Senior Developer


Joined: 27 Nov 2007
Posts: 152
Location: India

PostPosted: Tue Dec 18, 2007 5:09 am    Post subject: Reply with quote

Dear Plusminus, Nice work you have done.
i copied your code and i have created one activity which displays "SMSRecived".
when i run my program it is showing one error activity not defined by the manifest, also i have attached screen shot of the error and aslo i have attached my full coding, take a look.

Thanks and regards,
venkat



androidError.png
 Description:
 Filesize:  12.35 KB
 Viewed:  27941 Time(s)

androidError.png



SMSReceiver.rar
 Description:

Download
 Filename:  SMSReceiver.rar
 Filesize:  33.58 KB
 Downloaded:  399 Time(s)

Back to top
View user's profile Send private message
kadair
Junior Developer
Junior Developer


Joined: 16 Dec 2007
Posts: 16
Location: Cincinnati OH, United States

PostPosted: Tue Dec 18, 2007 5:16 am    Post subject: Reply with quote

Hi Venkat,

Would you mind posting your Android manifest file? For some reason I'm having issues downloading the source. Without looking at it, I would suggest double checking the packages in the manifest and if everything looks okay there, you may just need to delete your run configurations for that project. If you're not sure how to do that let me know and I can post a quick example.

I'll also try to download the source again so that I can take a closer look.

Regards,
Ken

_________________
"Your imagination is your preview of life's coming attractions." - Einstein

http://www.AppSocial.com


Last edited by kadair on Tue Dec 18, 2007 5:44 pm; edited 1 time in total
Back to top
View user's profile Send private message Visit poster's website
venkat
Senior Developer
Senior Developer


Joined: 27 Nov 2007
Posts: 152
Location: India

PostPosted: Tue Dec 18, 2007 5:33 am    Post subject: Reply with quote

Hi kadair Smile
Thanks for ur reply, i don't how to delete run configuration for that project. i hava attached mysource once again. try to download new one.

regads,
venkat



SMSReceiver.rar
 Description:

Download
 Filename:  SMSReceiver.rar
 Filesize:  33.58 KB
 Downloaded:  498 Time(s)

Back to top
View user's profile Send private message
kadair
Junior Developer
Junior Developer


Joined: 16 Dec 2007
Posts: 16
Location: Cincinnati OH, United States

PostPosted: Tue Dec 18, 2007 5:48 am    Post subject: Reply with quote

Venkat,

I was able to download and run your source this time. Go ahead and right-click on your project (SMSReceiver) in Eclipse. Select "Run As...", then the "Open Run Dialog..." option. You should see a pop-up that says "Create, manage, and run configurations" at the top. You need to select all of the projects under "Android Application" in the left menu and then click on the red "X" above. It will delete all of your "run configurations" for all of your Android projects. I would post some images if I had more time. Please feel free to shoot me a private message if you need further assistance. Hopefully, this will take care of you though.

Regards,
Ken

_________________
"Your imagination is your preview of life's coming attractions." - Einstein

http://www.AppSocial.com


Last edited by kadair on Tue Dec 18, 2007 5:44 pm; edited 1 time in total
Back to top
View user's profile Send private message Visit poster's website
venkat
Senior Developer
Senior Developer


Joined: 27 Nov 2007
Posts: 152
Location: India

PostPosted: Tue Dec 18, 2007 5:53 am    Post subject: Reply with quote

Hi kadair,
now it works fine. thanks for ur help. Smile Thank you very much once again.


Regads,
venkat.
Back to top
View user's profile Send private message
Nitinkcv
Developer
Developer


Joined: 29 Nov 2007
Posts: 29

PostPosted: Sat Dec 22, 2007 7:13 pm    Post subject: How about sending Sms!! Reply with quote

Hi all,

Was just wondering whether the updated SDK allows us to send out SMS's.

Thanks,
Nitin
Back to top
View user's profile Send private message Send e-mail AIM Address Yahoo Messenger
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2439
Location: College Park, MD

PostPosted: Sun Dec 23, 2007 2:55 pm    Post subject: Reply with quote

Hello Nitinkcv,

basically it is possible. There is a Source SMSManager providing the following function:
Java:
public void sendTextMessage(String destinationAddress, String scAddress, String text, Intent sentIntent, Intent deliveryIntent, Intent failedIntent)


But how to send an SMS without a GSM-Connection Wink
The Emulator probably simulates a success or a failure ... haven't tried it yet. So I cannot say if this funcitonality is already full impelmented.

Regards,
plusminus

_________________
Please remember, that this board is give & take Smile

| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
mjpan
Freshman
Freshman


Joined: 24 Dec 2007
Posts: 4

PostPosted: Fri Dec 28, 2007 7:59 am    Post subject: Re: Recognize/React on incoming SMS Reply with quote

thanks for the great tutorial.

one question, though. right now you simply use a NotificationManager to display the incoming text message. How can the message be passed to the Activity Question

currently i have an activity, which is put onPause(), and using the IntentReceiver, is resumed through onResume(). the Activity's mIntent, however, has null as the extras bundle, despite my having explicitly put it into the extras via intent.putExtras(bundle). perhaps because the activity was on pause, its mIntent is the one that originally created it, and not the one that resumed it Question
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2439
Location: College Park, MD

PostPosted: Fri Dec 28, 2007 1:52 pm    Post subject: Re: Recognize/React on incoming SMS Reply with quote

Hello mjpan,

mjpan wrote:
Perhaps because the activity was on pause, its mIntent is the one that originally created it, and not the one that resumed it Question


Don't think so, because Intents "die" after being used.

What do you mean with "mIntent" Question == this.getIntent() Question

Try putting some invented Category to the Intent and check if it arrives at the other side of the 'tunnel'. Like:
Java:
     i.addCategory("MY_CATEGORY");

        // And on the other side of the road:
        for(String s : this.getIntent().getCategories())
          Log.d("CATEGORY_TAG", "CAT= " + s);


Regards,
plusminus

_________________
Please remember, that this board is give & take Smile

| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
mjpan
Freshman
Freshman


Joined: 24 Dec 2007
Posts: 4

PostPosted: Fri Dec 28, 2007 6:06 pm    Post subject: Re: Recognize/React on incoming SMS Reply with quote

Hi plusminus,
Thanks for getting back to me. Yes, by mIntent, i mean this.getIntent(), where "this" is the Activity being resumed. I'm using the debugger to inspect the objects, and "mIntent" is the name of the member field of the Activity object. I have also verified (using the debugger) that if my application is NOT running, then mIntent.getExtras() is the one created in SMSReceiver, while if application is already running, then mIntent.getExtras() is null. Do you know how to open a ticket against this bug in Android?
Thx
mjpan

plusminus wrote:
Hello mjpan,

What do you mean with "mIntent" Question == this.getIntent() Question

Try putting some invented Category to the Intent and check if it arrives at the other side of the 'tunnel'. Like:
Java:
     i.addCategory("MY_CATEGORY");

        // And on the other side of the road:
        for(String s : this.getIntent().getCategories())
          Log.d("CATEGORY_TAG", "CAT= " + s);


Regards,
plusminus
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2439
Location: College Park, MD

PostPosted: Fri Dec 28, 2007 6:10 pm    Post subject: Reply with quote

Hello mjpan,

did you try the Category-Thing Question

There is no official Bug-Tracking-System yet, but on my Bugs posting them to the GoogleGroups and hoping a moderator would see them was fine ^^.

Regards,
plusminus

_________________
Please remember, that this board is give & take Smile

| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
Display posts from previous:   
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials All times are GMT + 1 Hour
Goto page 1, 2, 3, 4, 5  Next
Page 1 of 5

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


© 2007, Android Development Community
All rights reserved.
Powered by phpBB.