Receiving in app SMS messages only from certain sp

2019-05-23 16:17发布

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();

    }
}
}

3条回答
迷人小祖宗
2楼-- · 2019-05-23 16:45

Just put bellow

    String body=....
    if(sender.equals(phoneNumber)) {

                abortBroadcast() then do something...
    }

Be sure to do abortBroadcast as soon as possible, since if you do to many operations before it, the original inbox will pick up the message.

查看更多
欢心
3楼-- · 2019-05-23 16:45
if("123456789".equals(sender))
{
 //do something
}
查看更多
爷的心禁止访问
4楼-- · 2019-05-23 17:04

You should do:

String body=....
if(PhoneNumberUtils.compare(sender, phoneNumber)) {

            abortBroadcast() then do something...
}
查看更多
登录 后发表回答