user5102612
user5102612

Reputation: 121

Notification onClick Intent sends wrong data to Activity

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

Answers (1)

David Wasser
David Wasser

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 Notifications available at the same time, then you need to make sure that you create unique PendingIntents 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

Related Questions