How do you rate this blog

Thursday, May 24, 2012

Simple SMS - Receive Feature


    In the previous post I had told about the method to send sms, in this post I will tell about how to receive SMS and how to test out the application.

We will use the same application which we used for sending SMS, here we will add one more class called Rec which will extend BroadcastReceiver have code to receive application.  Once you do this you need to implement onRecieve method as shown below and write an intent filter which will allow it to receive SMS.
/*to obtain the message*/        
public void onReceive(Context C, Intent I) {
                               
                                Bundle B=I.getExtras();
                                SmsMessage[] msgs=null;
                                String sms_str="";
/* Receive SMS and display*/                                   
                                if(B !=null){
                Object[] pdus=(Object[]) B.get("pdus");
                msgs=new SmsMessage[pdus.length];
                for(int i=0;i<msgs.length;i++){
/*To convert the sms which is in PDU format*/
                msgs[i]=SmsMessage.createFromPdu((byte[])pdus[i]);
/*To display the number from which the message was sent*/
                sms_str+="Recieved SMS From : "+msgs[i].getOriginatingAddress() +" : ";
                sms_str+=msgs[i].getMessageBody().toString()+"\n";
                                                }
                Toast.makeText(C, sms_str, Toast.LENGTH_LONG).show();
                                }
The code for receive class will look like in the snapshot given below.



Now we need to modify the manifest.xml file to include the following

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

Which will display the message in the application and will display it as a Toast.
Also include the below code so that the application has the access to receive sms.
<uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
So the manifest file will look like in the image given below.



Once these are done the application is ready to receive the SMS. So now the question is how to test it. Inorder to do test if the application receives the the eclipse has a DDMS perspective which allows you to send voice or sms to the emulator. To access DDMS you can refer to the following link DDMS Link. Now type in the emulator number in this case it is 5554 and send as SMS as shown in the snapshot below. 



Once you click on Send button in DDMS you can see that the SMS is received in the application as shown in the snapshot shown below.


No comments:

Post a Comment