如何在安卓系统中更新现有通知?

7

我正在使用以下代码显示通知。当通知显示时,如果我点击通知,则会跳转到相应的活动。

void Notify(String notificationTitle, String notificationMessage){
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.noti, notificationTitle,System.currentTimeMillis());

        Intent notificationIntent = new Intent(this, SmsActivity.class);

        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent intent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        notification.setLatestEventInfo(this, notificationTitle,notificationMessage, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notification);
       } 

现在我想更新通知的文本。我该怎么做?

1
我认为你应该使用相同的ID发布另一个通知,这样它就会被更新。 - Emil
5个回答

9
你可以尝试这个。
    //First time    
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                        .setContentText(context.getString(R.string.notif_text))
                        .setContentTitle(title)
                        .setSmallIcon(R.drawable.ic_action_alarm_2)
                        .setAutoCancel(false)
                        .setOngoing(running)
                        .setOnlyAlertOnce(true)
                        .setContentIntent(
                                PendingIntent.getActivity(context, 10, 
                                        new Intent(context, YourActivity.class)                                 
                                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
                                0)
                        )

            notificationManager.notify(id, builder.build());

     //Second time

            builder.setContentTitle(title);
            notificationManager.notify(id, builder.build());

id 的值是多少? - osimer pothe


2

您可以通过在 Notify(String notificationTitle, String notificationMessage) 方法中发送不同的文本来更新通知的文本。


1
你能进一步解释一下吗?如果可能的话,展示一些代码!(在我的情况下,我需要在按钮点击时更新通知中按钮上的ContentText) - Thorvald

2
这里提出的方法存在一个问题,如果用户已经回应了这个通知,他可能会再次看到它,所以最好只显示一次。
因此,我不建议使用这个API来更新你的通知。
如果你正在为此目的使用它,你可能只是把一个漏洞换成了另一个。

1

不要将0作为通知ID传递,发送其他数字并使用相同的ID触发另一个通知。现有通知将被更新。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接