问题
I'm creating a notification from a Service that has an intent with an extra integer. For some reason, this isn't as easy as it seems. This is what I'm doing:
Notification notification = new Notification(R.drawable.notification_icon, "Title", 0);
Intent relaunchIntent = new Intent(this, SomeClass.class);
relaunchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
relaunchIntent.putExtra("load", getId());
notification.setLatestEventInfo(this, "Title", "Tap here to open", PendingIntent.getActivity(this, 0, relaunchIntent, 0);
notificationManager.notify(1234, notification);
And then from SomeClass, it reads like this...
if(getIntent().getExtras() != null)
load(getIntent().getExtras().getInt("load", -1));
What's weird is that I get inconsistent results when I read the value from the getInt()
method. Sometimes I get values of things I set in a previous notifications. For example, I get a value of 3 when I had set that extra to be 4. I know this is very confusing and strange, which is why I'm wondering if anyone has experienced anything like this and what you may have done to fix it. Thanks!
回答1:
You should try using PendingIntent.FLAG_UPDATE_CURRENT when you call PendingIntent.getActivity
. From the documentation:
This can be used if you are creating intents where only the extras change, and don't care that any entities that received your previous PendingIntent will be able to launch it with your new extras even if they are not explicitly given to it.
I ran into this issue myself, and found the answer from a comment on this answer.
来源:https://stackoverflow.com/questions/7098893/cant-put-extras-for-an-intent-in-notification