如何在Android应用程序中一次只显示一个通知

3
我使用以下代码来显示通知。
private void SendNotification(String notificationTitle, String notificationMessage) 
{
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
android.app.Notification notification = new android.app.Notification(R.drawable.ic_launcher, notificationMessage,
        System.currentTimeMillis());

Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.putExtra("notif_id", "5100");

//Setting the single top property of the notification and intent.
notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS; 
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(MainActivity.this, notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify((int)System.currentTimeMillis(), notification);
}

每当有新的通知出现时,应该删除之前的通知并显示新的通知。任何线索都将有所帮助。提前感谢您。

要取消之前的 PendingIntent(如果存在),请使用 PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT)。只需替换附加项,使用 PendingIntent.FLAG_UPDATE_CURRENT。 - AlexBcn
AlexBcn,尝试了两种选项,但都没有删除之前的消息。谢谢回复。 - osum
2个回答

6
每次生成通知时都使用不同的ID(System.currentTimeMillis()),请将其更改为单个ID。 notificationManager.notify(0, notification); 向状态栏中显示通知。如果您的应用程序已经发布了具有相同ID的通知并且尚未被取消,则会被更新的信息替换。 NotificationManager.html

不要忘记将System.currentTimeMillis()强制转换为int类型。 - D. B.

2

在发布新版本之前,有一种方法可以清除应用程序的所有通知。尝试以下方法:

notificationManager.cancelAll();

要清除特定的通知,可以这样做:
notificationManager.cancel(notification_id);

这个解决了,谢谢hopetribe,但我只想知道是否有任何选项可以仅使用标志来完成这个。 - osum

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