Nicofisi
Nicofisi

Reputation: 1113

How to update time of an Android notification

I've got an Android notification which is updated every few minutes.

Firstly I create a Builder like that:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);

And then, for first time when I show it and every time I update it, I use this code:

mBuilder.setContentTitle("Title");
mBuilder.setContentText("Text");
NotificationManager manager = (NotificationManager)
        context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, mBuilder.build());

But in the upper right corner of notification, Android still shows the time of when it was first displayed to the user. I'd like it to show the time of the last update. I know that it's possible because Facebook's Messenger app does that - changes the displayed time when a new message is sent.

How can I achieve that?

Currently: test

Upvotes: 8

Views: 7398

Answers (2)

Aditya Patil
Aditya Patil

Reputation: 1486

You can show time using below code

val notificationBuilder = NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle(title)
        .setContentText(body)
        .setColor(resources.getColor(R.color.colorPrimary))
        .setAutoCancel(true)
        .setSound(soundUri)
        .setContentIntent(pendingIntent)
        .setWhen(System.currentTimeMillis())

Upvotes: 0

Kiskae
Kiskae

Reputation: 25573

You're probably looking for NotificationCompat.Builder#setWhen(long). Supplying it with System.currentTimeMillis() should update the timestamp to the current time.

In addition if you want that timestamp to appear on Android N or higher, you need to call NotificationCompat.Builder#setShowWhen(true) at some point because it defaults to false.

Source: https://developer.android.com/reference/android/app/Notification.html#when

Upvotes: 15

Related Questions