Old intent in activity started from notification

Issue

I’m creating intent like this

val tapIntent  Intent(context, TaskActivity::class.java).apply {
    flags  Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val id  createID()
tapIntent.putExtra("timestamp", currentTime)
val notificationIntent: PendingIntent  PendingIntent.getActivity(context, 0, tapIntent, 0)
val builder  NotificationCompat.Builder(context, "com.task")
    .setSmallIcon(R.drawable.ic_android_black_24dp)
    .setContentTitle(context.resources.getString(R.string.new_task_available))
    .setContentIntent(notificationIntent)
    .setAutoCancel(true)
    .setPriority(NotificationCompat.PRIORITY_MAX)
with(NotificationManagerCompat.from(context)) {
    notify(id, builder.build())
}

This notifications are generated few times a day. And when testing it, I’ve found out that if I’m not closing activity, but just swiping out of it, next time I open this activity from intent, I see that intent stores timestamp of a previous notification and not a current one.

Code for reading data from intent is quite simple:

val timestamp  intent.getLongExtra("timestamp", System.currentTimeMillis())
val hourFormatter  SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault())
Toast.makeText(this, hourFormatter.format(Date(timestamp)), LENGTH_LONG).show()

As far as I understand Intent.FLAG_ACTIVITY_CLEAR_TASK should clear all the old info. So I don’t understand why this is happening. What sould I do to receive current intent instead of the original one?

Solution

When generating the PendingIntent for the Notification, you need to do this:

PendingIntent.getActivity(context, 0, tapIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT)

Otherwise you will just be using the previous (old) PendingIntent instead of creating a new one.

Answered By – David Wasser

Leave a Comment