Breaking News

29.Receiving SMS in android

Receiving SMS in android
Receiving SMS





Receiving SMS in android


∎Besides sending SMS messages from our Android applications, we can also receive incoming SMS messages from within our applications by using a BroadcastReceiver object. 

∎This is useful when we want our application to perform an action when a certain SMS message is received. 

∎For example, we might want to track the location of our phone in case it is lost or stolen. 

∎In this case, we can write an application that automatically listens for SMS messages containing some secret code. 

∎When that message is received, the app can send an  SMS message containing the location's coordinates back to the sender.

∎When a device receives a new SMS message, a new broadcast Intent is fired with an action android .provider.Telephony.SMS_RECEIVED 

∎To listen for this action, our application must register a BroadcastReceiver. 

∎That is, we need to create a receiver and then register it in the manifest file. After we register the receiver, our application is notified whenever an SMS message is received. 



Steps Needed

1.Create a subclass of BroadCastReceiver class

2.Override it’s onReceive( ) method

3.In order to receive broadcast announcements for a particular event, register the class in manifest file specifying the intent-filter type 

“android.provider.Telephony.SMS_RECEIVED” 




The code for onReceive() Method


public class MySmsReceiver extends BroadcastReceiver {
@Override
 public void onReceive(Context context, Intent intent) {
  Toast.makeText(context, "Receiver Called!!!", Toast.LENGTH_SHORT).show();
        Log.i("BROADCAST RECEIVER","OnREC called");
  Bundle bundle = intent.getExtras();
  SmsMessage[ ] msgs = null;
  String str=“”;
        if (bundle != null) {
   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]);
                str += "SMS from " + msgs[i].getOriginatingAddress();
    str += ":";
    str += msgs[i].getMessageBody().toString();
    str += "\n";
   }
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
   Log.i("BROADCAST REC","Details:"+str);
  }
 }
}





Code Explained


∎The broadcast Intent that is fired after receiving a new SMS message includes a Bundle containing information about the received message.

∎Each SMS message is stored in an Object array. If the SMS message is fewer than 160 characters then the array has one element. If an SMS message contains more than 160 characters the message is split into multiple smaller messages and is stored as multiple elements in the array.

∎Internally each element in the Object array is actually an SMS PDU

PDU stands for Protocol Data Unit and is used to encapsulate the SMS message.

∎ The array of SMS PDUs is thereafter converted into an array of SmsMessage objects.

∎To convert each PDU byte array into a SmsMessage object, the SmsMessage.createFromPdu() method is called, passing in each byte array.

∎The information of all received messages is gathered in the SmsMessage array msgs.

∎Each array element represents the complete information of a single-part of received SMS that includes the originating address—the phone number, timestamp, and the message body.


∎The following methods are used to fetch the SMS information from the SmsMessage array elements:

     🗆getOriginatingAddress()—Fetches the phone number of the SMS recipient

     🗆getTimestampMillis()—Fetches the time at which the SMS is received

     🗆getMessageBody()—Fetches the message body




Specifying The Permission


∎ Our application has to seek permission to receive incoming SMS messages.

∎To do this, we have to add the permission android.permission.RECEIVE_SMS  to the manifest file:

<uses-permission android:name="android.permission.RECEIVE_SMS" />

∎To listen for incoming messages, we need to register our Broadcast Receiver class using an Intent Filter called android.provider.Telephony.SMS_RECEIVED  action String.


<receiver
    android:name=".MySmsReceiver"
    android:exported="true" >
    <intent-filter android:priority="2147483647">
        <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
    </intent-filter>
</receiver>




What is android: priority?


∎The android: priority is an integer indicating which receiver has higher priority in processing the incoming broadcast message.


∎The higher the number, the higher the priority and the sooner that receiver can process the broadcast message.


∎We are setting it to the highest value 2147483647 so that our app gets the highest priority in getting the message.


∎By default, whenever an SMS arrives every time both our application and the built-in application receive it.


∎This is because when an SMS message is received, all applications (including the Messaging application) on the Android device take turns handling the incoming message.


∎Sometimes, however, this is not the behavior we want.

 ∎For example, we might want our application to receive the message and prevent it from being sent to other applications.

∎This is very useful, especially if we are building some kind of tracking application.


∎To do this we require 2 steps:

            1.Set android: priority to a high number like 214748367 

            2.From the body of onReceive( ) method in our receiver, we can simply call the abortBroadcast() method which belongs to our superclass BroadCastReceiver.






Thanks . . .


⬜⬜⬜



No comments