Receiving in app SMS messages only from certain specified numbers

和自甴很熟 提交于 2019-12-12 10:08:34

问题


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

    }
}
}

回答1:


You should do:

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

            abortBroadcast() then do something...
}



回答2:


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:


if("123456789".equals(sender))
{
 //do something
}


来源:https://stackoverflow.com/questions/18100610/receiving-in-app-sms-messages-only-from-certain-specified-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!