Wednesday, July 20, 2011

How to receive sms in android ?

In this article, I will cover how to write a simple app that can receive SMS. This will also serve as a sample implementation of a broadcast receiver in android.Steps

  • 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.