仅从某些指定号码中接收应用程序SMS消息

仅从某些指定号码中接收应用程序SMS消息

本文介绍了仅从某些指定号码中接收应用程序SMS消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近设置了一个将接收短信的应用程序,然后将其显示为主要活动上的祝酒词。一旦应用收到短信,它将中止广播,并阻止消息进入收件箱。

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.

目前,它会处理手机收到的所有消息,但我会希望它仅执行工作并在收到特定号码的SMS时显示吐司。我知道这是将if语句放入我的接收器代码中的一种情况,但是我不太确定应将其放置在何处。

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:

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

    }
}
}


推荐答案

您应该这样做:

You should do:

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

            abortBroadcast() then do something...
}

这篇关于仅从某些指定号码中接收应用程序SMS消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 00:55