如何使用 PendingIntent 将已发送短信的数据传递给 BroadcastReciever?

How to pass data of sent SMS message using PendingIntent to BroadcastReciever?

我想在发送大量短信时将一些数据传递给 BroadcastReceiver 以指示哪个消息是 sent/delivered。

我尝试使用带有不同标志的标准 PendingIntent 但得到了错误的结果(BroadcastReceiver 总是得到 first/last 额外的意图)。有谁知道如何在使用 SmsManager 发送 SMS 消息时将数据传递给 BroadcastReceiver

发送短信的函数:

private void sendSMS(SmsRequest _smsRequest) {

        Intent sentInt = new Intent(SmsNotificationSending.SENT);
        sentInt.putExtra("SMS_ID", _smsRequest.getmId());

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentInt, 0);

        Intent delivInt = new Intent(SmsNotificationSending.DELIVERED);
        delivInt.putExtra("SMS_ID", _smsRequest.getmId());

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, delivInt, 0);

        registerReceiver(sendBroadcastReceiver, new IntentFilter(SENT));
        registerReceiver(deliveryBroadcastReceiver, new IntentFilter(DELIVERED));

        SmsManager
                .getSmsManagerForSubscriptionId(1)
                .sendTextMessage(_smsRequest.getmRecipientNumber(),
                        null,
                        _smsRequest.getmMessage(),
                        sentPI,
                        deliveredPI);
    }

我的BroadcastReceiverclass:

public class DeliveryReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        switch (getResultCode()) {
            case Activity.RESULT_OK:
                Log.d("sms", "Broadcast received: " + intent.getAction());
                Log.d("sms" ,"Sms was delivered" + intent.getIntExtra("SMS_ID", -1));
                break;
            case Activity.RESULT_CANCELED:
                Log.d("sms" ,"Sms was not delivered");
                break;
        }

    }
}

sendSms() 一个接一个地多次调用,在日志中我收到了很多应该收到的广播,但只有第一个 SMS_ID 的 SMS 消息。 请帮帮我!

此代码不符合您的要求:

    Intent sentInt = new Intent(SmsNotificationSending.SENT);
    sentInt.putExtra("SMS_ID", _smsRequest.getmId());
    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentInt, 0);

    Intent delivInt = new Intent(SmsNotificationSending.DELIVERED);
    delivInt.putExtra("SMS_ID", _smsRequest.getmId());
    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, delivInt, 0);

问题是这段代码每次都重复使用相同的 PendingIntent(它在 extras 中有第一个 SMS_ID)。

你需要做的是在每次执行这段代码时创建一个新的PendingIntent。为此,您需要执行以下一项(或多项)操作:

  • 每次调用 PendingIntent.getBroadcast() 时使用不同的 requestCode(第二个参数)
  • 每次在 Intent 中使用不同的 ACTION(您可以通过在使用 new Intent(...) 实例化 Intent 时在 ACTION 中包含 SMS_ID 来做到这一点

这将确保每次创建唯一的 PendingIntent,这将解决您的问题。