How to properly update a notification post api 11?

和自甴很熟 提交于 2019-12-02 21:44:40
dbro

I resolved this issue by calling setWhen(0) on my Notification.Builder. It seems Android's default value for this argument doesn't suit updating bits of the notification view without the entire notification fading out / in.

Notification.Builder builder = new Notification.Builder(c)
                .setContentTitle("Notification Title")
                .setSmallIcon(R.drawable.ic_notification_icon)
                .setProgress(max_progress,current_progress,false)
                .setWhen(0);
                notification = builder.getNotification();

mNotificationManager.notify(NOTIFICATION_ID, notification);

Update:

As WolframRittmeyer stated, using when=0 is not an elegant way. I formed a solution like following:

if(mNotif == null) {
//either setting mNotif first time
//or was lost when app went to background/low memory
    mNotif = createNewNotification();
}
else {
    long oldWhen = mNotif.when;
    mNotif = createNewNotification();
    mNotif.when = oldWhen;
}
mNotificationManager.notify(NOTIFICATION_ID, mNotif);

What you are doing is correct, you're just missing the flags you can set. I don't know your particular notification implementation but you might consider using:

setOngoing(boolean ongoing)

or

setOnlyAlertOnce(boolean onlyAlertOnce)
derflocki

I'm guessing (since I had the same trouble just now) that you are using a RemoteView in your notification. I managed to update the notification without it flashing like this:

RemoteViews views;
if( this.mNotification == null) {
    views = new RemoteViews(getPackageName(), R.layout.notification);
    this.mNotification = new Notification.Builder(this)
        .setContent(views)
        .setSmallIcon(R.drawable.status_icon)
        .setContentIntent(mNotificationAction)
        .setOngoing(true)
        .setOnlyAlertOnce(true)
        .getNotification();
} else {
    views = this.mNotification.contentView;
}

Thanks to @seanmonstar for answering Refresh progress bar in notification bar.

Philipp E.

The solution described here works well: Updating an ongoing notification quietly

The key is to use to reuse the builder and setOnlyAlertOnce(true):

if (firstTime) {
  mBuilder.setSmallIcon(R.drawable.icon)
  .setContentTitle("My Notification") 
  .setOnlyAlertOnce(true); 
  firstTime = false;
} 
mBuilder.setContentText(message)
.setProgress(100, progress, true);

mNotificationManager.notify(mNotificationId, mBuilder.build());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!