Tuesday, April 17, 2012

Intercept SMS with Broadcast Receiver

Hi developers,

in Android Broadcast Receivers are used to listen for broadcast Intents. A Broadcast Receiver needs to be registered, either in code or within the application manifest. (in this case is registered in the manifest)
When registering a Broadcast Receiver you must use an Intent Filter to specify which Intents it is listening for.

We use BroadcastReceiver to intercept SMS.
See the code below

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMSBroadcastReceiver extends BroadcastReceiver{
        @Override
 public void onReceive(Context context, Intent intent) {
  Bundle bundle = intent.getExtras();
  SmsMessage[] msgs = null;
  StringBuilder str = new StringBuilder();
  if (bundle != null) {
   // --- retrieve the received SMS here ---
   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.append("SMS from " + msgs[i].getOriginatingAddress());
    str.append(" :");
    str.append(msgs[i].getMessageBody().toString());
    str.append("\n");
   }
   // ...we show sms here...
   Toast.makeText(context, str.toString(), Toast.LENGTH_SHORT).show();
  }
 }
}

As you can see, we extends from BroadcastReceiver and override the method onReceive where we retrieve information about the received SMS.

In the manifest you must define the RECEIVE_SMS uses-permission, register the receiver (our class SMSBroadcastListener) and his intent-filter (SMS_RECEIVED):



    

    
    

    
        
            
                
            
        
    




They will be started automatically when a matching Intent is broadcast, in practice when received an SMS you will see a Toast with SMS information.

No comments :

Post a Comment