Android PendingIntent Extra

androidandroid-intentandroid-service

I'm trying to send SMS messages from an Android App. I'm using PendingIntent to so I can use a Broadcast Receiver to check if it was sent ok. As the sendTextMessage call will be done per SMS, I need to send some "extra" data to identify the actual SMS, so as my broadcast receive can do some work on a specific SMS Message.

Here is my sending code:

        String SENT = "SMS_SENT";

        Intent sentIntent = new Intent(SENT);
        sentIntent.putExtra("foo", "BAR");
        PendingIntent sentPI = PendingIntent.getBroadcast(baseContext, 0,
            sentIntent, 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(baseContext, 0,
            new Intent(DELIVERED), 0);

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(smsMessage.getNumber(), null, smsMessage.getText(), sentPI, deliveredPI); 

The problem is that in my BroadCast receiver, it can't seem to read my Extra "foo":

    public class SMSSentBroadcastReceiver extends BroadcastReceiver {

   @Override
       public void onReceive(Context arg0, Intent intent) {
       String smsID = intent.getStringExtra("foo");
       ......
       }
    }

smsID just becomes null.

My broadcast receiver is registered like so:

baseContext.registerReceiver(new SMSSentBroadcastReceiver(), new IntentFilter("SMS_SENT"));

Given that the intent filter is working, what am I doing wrong? Why aren't the extras sent as well?

Any help is appreciated. Thanks

Best Answer

What I suspect has happened (at least, it's happened to me), is that you're using the SMS_SENT intent somewhere else prior, whereby at that time, that intent doesn't have "foo" in the extras. Calling PendingIntent.getBroadcast with the same intent and request code will return you the original pending intent.

If it's actually meant to be the same intent, you need to use something like a PendingIntent.FLAG_UPDATE_CURRENT to update the intent with the new extras. If it's not suppose to be the same intent, it should have a different request code, so that it doesn't match the other intent (which is why feeding in a unique request code worked).