barmaley barmaley - 4 months ago 45
Android Question

How to send data through PendingIntent to Broadcast?

I'm trying to send via

PendingIntent
some extra data, like:

MyMessage message;
//...
Intent intent;
SmsManager sms = SmsManager.getDefault();
intent = new Intent(Constants.SENT_PLAIN);
intent.putExtra(Constants.EXTRA_RAW_ID, message.getId()); //putting long id (not -1L)
PendingIntent sentPI = PendingIntent.getBroadcast(activity, 0, intent, 0);
intent = new Intent(Constants.DELIVERED_PLAIN);
intent.putExtra(Constants.EXTRA_RAW_ID, message.getId());
PendingIntent deliveredPI = PendingIntent.getBroadcast(activity, 0, intent, 0);
sms.sendTextMessage(phoneNumber, null, message.getBody(), sentPI, deliveredPI);


Then in
Broadcast
trying to catch data:

@Override
public void onReceive(Context context, Intent intent) {
String message, prefix = "";
String action = intent.getAction();
long id = intent.getLongExtra(Constants.EXTRA_RAW_ID, -1L); //here I receive id=-1

// blah-blah....
}


I see that
Broadcast
onReceive()
called - which means that
Broadcast
registered in a proper way, but still extras are empty.

Any ideas?

Answer

Put data in intent you are using in pending intent as Extras. You will get this intent in onReceive Method of BroadCast receiver. Try to define Pending intent as below.

PendingIntent sentPI = PendingIntent.getBroadcast(activity, 0, intent,PendingIntent.FLAG_CANCEL_CURRENT);