Search code examples
androidsmsbroadcastreceiver

Receiving in app SMS messages only from certain specified numbers


I've recently set up an app that will receive sms messages and then display them as a toast on the main activity. Once the app has received an SMS it will abort broadcast and stop the message from going into the inbox.

Currently it does this with all messages that the phone receives but I would like it to only carry out its job and display the toast when an SMS is received by a specific number. I know that it is a case of putting an if statement into my receiver code but I'm not too sure where abouts the it should be placed.

SmsReceiver.java:

public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Bundle extras = intent.getExtras();


    if (extras ==null)
        return;
    //toast
    Toast.makeText(context, "Received", Toast.LENGTH_LONG).show();

    Object[] pdus = (Object[]) extras.get("pdus");

    for (int i = 0; i < pdus.length; i++) {
        SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
        String sender = SMessage.getOriginatingAddress();
        String body = SMessage.getMessageBody().toString();

        Intent in = new Intent("SmsMessage.intent.MAIN").putExtra("get_msg", sender+":"+body);

        context.sendBroadcast(in);
        this.abortBroadcast();

    }
}
}

Solution

  • You should do:

    String body=....
    if(PhoneNumberUtils.compare(sender, phoneNumber)) {
    
                abortBroadcast() then do something...
    }