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?
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);
as said on pending intent :
Because of this behavior, it is important to know when two Intents are considered to be the same for purposes of retrieving a PendingIntent. A common mistake people make is to create multiple PendingIntent objects with Intents that only vary in their "extra" contents, expecting to get a different PendingIntent each time. This does not happen. The parts of the Intent that are used for matching are the same ones defined by Intent.filterEquals
. If you use two Intent objects that are equivalent as per Intent.filterEquals
, then you will get the same PendingIntent for both of them.
There are two typical ways to deal with this.
If you truly need multiple distinct PendingIntent objects active at
the same time (such as to use as two notifications that are both shown
at the same time), then you will need to ensure there is something
that is different about them to associate them with different
PendingIntents. This may be any of the Intent attributes considered by
Intent.filterEquals
, or different request code integers supplied to
getActivity(Context, int, Intent, int)
, getActivities(Context, int, Intent\[\], int)
, getBroadcast(Context, int, Intent, int)
, or
getService(Context, int, Intent, int)
.
If you only need one PendingIntent active at a time for any of the
Intents you will use, then you can alternatively use the flags
FLAG_CANCEL_CURRENT
or FLAG_UPDATE_CURRENT
to either cancel or modify
whatever current PendingIntent is associated with the Intent you are
supplying.