Saturday, November 3, 2012

How To Receive SMS in Android


In this tutorial we will learn how to Receive a SMS and retrieve the Message and Sender's Phone Number.

To learn How to Send SMS read this How to Send SMS

We need to have a receiver class that will extend BroadcastReceiver class.
To receive SMS we to declare <uses-permission android:name="android.permission.RECEIVE_SMS"> in manifest file

Some More Good  Android Topics

Create a new Class SMSReceiver
In manifest we need to register  the SMSReceiver like this

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

Your manifest file should look like this



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
 
 <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>        
 
        <receiver android:name=".SmsReceiver"> 
            <intent-filter> 
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" /> 
            </intent-filter> 
        </receiver>
 
    </application>
    <!-- Permission to Receive SMS  -->
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>
 
 

SMSReceiver class


public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String messageReceived = "";            
        if (bundle != null)
        {
            //---retrieve the SMS message received---
           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]);                
                messageReceived += msgs[i].getMessageBody().toString();
                messageReceived += "\n";        
            }
 
            //---display the new SMS message---
            Toast.makeText(context, messageReceived, Toast.LENGTH_SHORT).show();
            // Get the Sender Phone Number
           String senderPhoneNumber=msgs[0].getOriginatingAddress ();   
       }                         
    }
}

To get the Sender's Number use msgs[0].getOriginatingAddress ()


To learn How to Send SMS read this How to Send SMS



 

New Advance Topics:
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swap Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation

 Beginning With Android
      Android : Introduction                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views


Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage
Working With Incoming Calls                                             DataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog







9 comments:

  1. I like the article on the topic due to this reason it is seen that other readers are showing their interest by commenting on it.
    sms message

    ReplyDelete
    Replies
    1. Android Tutorials For Beginners: How To Receive Sms In Android >>>>> Download Now

      >>>>> Download Full

      Android Tutorials For Beginners: How To Receive Sms In Android >>>>> Download LINK

      >>>>> Download Now

      Android Tutorials For Beginners: How To Receive Sms In Android >>>>> Download Full

      >>>>> Download LINK uh

      Delete
  2. how can i get one character only ????

    ReplyDelete
  3. i had an error on String senderPhoneNumber=msgs.getOriginatingAddress ();
    it says that it cannot invoke getOriginatingAddress() on the array type SmsMessage[]
    how can i fix this? thanks :)

    ReplyDelete
    Replies
    1. Hi Baby Ace
      thanks for letting me know that error.
      You should write the code like below to get the sender phone number.

      String senderPhoneNumber=msgs[0].getOriginatingAddress ();

      Delete
  4. How can I detect which SIM ( Samsung Dual SIM phone ) has received SMS ? Its very important to have dual sim for me in this app.

    Thanks in advance

    ReplyDelete
    Replies
    1. is there a way to read messages from dual sim phone ?

      Delete
  5. Nice tutorial.

    It is easy to make this app take any action on receipt of an sms (eg. make it reply with an automated message). My question is, is there a way to make it take an action on receipt of the first message and then wait for a second message from the same number before taking a second action (say, replying with another automated message)?

    Thanks

    ReplyDelete
  6. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! text marketing services

    ReplyDelete