Receive sms in own android application

To get notification of received sms we will use BroadcastReceiver.
So create new class with any name like SmsReceiver and extend it with BroadcastReceiver.
Code with description is given following.

public class SmsReceiver extends BroadcastReceiver {
public void onReceive(final Context context, Intent intent) {
// pdus contain all information about message.
Object[] pdus = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
StringBuilder strbMsgBody = new StringBuilder();
String msgAddress;
String msgTime;
int msgLength = messages.length;
for (int i = 0; i < msgLength; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
msgAddress = messages[i].getOriginatingAddress();
msgTime = messages[i].getTimestampMillis();
// We use loop to get message because message comes in chunks, so we combine it by StringBuilder
String msg = strbMsgBody.toString();
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
// If you want to stop message to save in inbox, uncomment following line.
// abortBroadcast();

In AndroidManifest.xml use following lines in <application></application> tag


            android:name=".SmsReceiver" >
            <intent-filter android:priority="2147483647" >
                <category android:name="android.intent.category.DEFAULT" />
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />

And set following permission in AndroidManifest.xml

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


Leave a comment

Your email address will not be published.