Android: 仅在触摸而不是通过 "clear all" 按钮时删除通知

Android: Delete Notification only when touched not throuch "clear all" Button

我的应用程序创建了一些通知,并在 PendingIntents 的帮助下将您带到一个特殊的 Activity。一切都很好,我唯一的问题是我希望仅在用户触摸通知时删除通知,而不是在用户使用 "Clear all" 按钮(通知栏顶部的 X)时删除通知。

目前我正在使用

setAutoCancel(true);

方法。它会在用户触摸通知时删除通知,也会在按下 "Clear ALl" 按钮时删除通知。我现在的问题是,是否有任何方法可以抑制 "Clear All" 按钮删除的通知。

如果你想知道我为什么想要这个,我创建了一个应用程序,它允许你使用通知作为一种提醒。 "Clear Button" 在这里很烦人,因为它会删除所有提醒通知。

感谢您的帮助,如果您需要任何其他代码,请写下来。

您可以通过将通知设置为正在进行,然后在 PendingIntent 触发时取消它来完成此操作。

Ongoing notifications cannot be dismissed by the user, so your application or service must take care of canceling them.

假设您使用 Notification.Builder 创建通知,只需在调用 build().

之前添加以下行
.setOngoing(true)

如果您希望删除通知,请使用发布通知时使用的相同 ID 在 NotificationManager 服务上调用 cancel()