如何使用PendingIntent将已发送的SMS消息的数据传递到BroadcastReciever?

时间:2019-07-03 20:48:45

标签: java android android-pendingintent smsmanager

在发送大量SMS时,我想将一些数据传递给BroadcastReceiver,以指示发送/发送的消息。

我尝试使用带有不同标志的标准PendingIntent,但得到了错误的结果(BroadcastReceiver总是获得意图的第一个/最后一个附加内容)。有人知道如何在使用BroadcastReceiver发送SMS消息的同时将数据传递到SmsManager吗?

发送短信的功能:

private void sendSMS(SmsRequest _smsRequest) {

        Intent sentInt = new Intent(Long.toString(System.currentTimeMillis()));
        sentInt.putExtra("SMS_ID", _smsRequest.getmId());

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

        Intent delivInt = new Intent(Long.toString(System.currentTimeMillis()));
        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);
    }

我的BroadcastReceiver班:

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消息的前SMS_ID个。 请帮帮我!

1 个答案:

答案 0 :(得分:0)

此代码无法满足您的要求:

    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(在附加功能中具有第一个SMS_ID)。

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

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

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