- Your receiver class must extend BroadcastReceiver and override onReceive() method. onReceive will be invoked by the android system whenever a sms arrives.
- To be able to receive sms, you must have the appropriate permissions defined in manifest file.
- You must register your receiver class in manifest file. You must also specify what intents your receiver is interested in. In our case, its the sms received intent
Source code
public class MessageReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context ctx, Intent intent) {
Log.d("MyApp:", "Message received");
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
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]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
Log.d("MyApp:",str);
}
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
}
for the list of available intents, refer sdk's platform /data/broadcast_actions.txt
Maybe in the next article, I will cover how to find the contact name of the sms sender.
Man, I just love your little tutorials! How do I get in touch with you? There is no contact form or "about" page.
ReplyDeleteGlad that you find it useful. You can always drop me an email to babusd@gmail.com.. Or just leave a comment/suggestion here..
ReplyDelete