Reputation: 121
I am using the newIntent to pass the correct taskId when a notification in my app is clicked. This is the code inside onReceive() of my broadcast receiver:
Intent newIntent = new Intent(context, TaskActivity.class);
int taskId = intent.getIntExtra("taskId", 0);
newIntent.putExtra("taskId", intent.getIntExtra("taskId", 0));
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle(intent.getStringExtra("NotificationTitle"))
.setContentText(intent.getStringExtra("NotificationText"))
.setSmallIcon(intent.getIntExtra("NotificationIcon", 0))
.setContentIntent(PendingIntent.getActivity(context, 0, newIntent, 0))
.build();
This is the code of the activity that receives the Intent
if (getIntent().hasExtra("taskId")) {
currentTask = dataSource.fetchTask(getIntent().getIntExtra("taskId", 0));
}
When I debug, the method getIntExtra() returns a different value than the one in onReceive() of the broadcast receiver.
Any ideas why this happens?
Thank you!
Upvotes: 4
Views: 1482
Reputation: 95578
When you create the Notification
, instead of this:
.setContentIntent(PendingIntent.getActivity(context, 0, newIntent, 0))
Do this:
.setContentIntent(PendingIntent.getActivity(context, 0, newIntent, PendingIntent.FLAG_UPDATE_CURRENT))
Your problem is that you are reusing the same PendingIntent
multiple times. You need to make sure that the "extras" in the PendingIntent
are updated every time you use one.
NOTE: If you have several Notification
s available at the same time, then you need to make sure that you create unique PendingIntent
s for each one. To do this, make sure that the requestCode
parameter (second argument in PendingIntent.getActivity()
) are different for each Notification
(you could, for example, use your taskId
as a unique requestCode
).
Upvotes: 19