如何修改使用 StartForeground 创建的通知?

How can I modify a Notification that is created with StartForeground?

我有一个服务需要 运行 作为前台服务。 为此,必须将通知链接到它。

当服务启动时,我将OnGoing设置为true,当用户与Notification交互以停止服务时,我想将当前的Notification更改为OnGoing(false)。 (因此,如果需要,用户可以关闭通知) 我希望通知仍然可见,以便用户可以从通知中再次启动服务。

通常情况下,我不得不使用 NoficiationManager 来使用特定 ID 进行 .Notify,然后再对其进行修改。 但是,通过调用 StartForeground(flags, notification),没有设置 ID 的选项。

如何将 OnGoing(true) 通知(从 StartForeground 调用开始)修改为 OnGoing(false)?

我认为您的想法是正确的:您必须使用一个 ID,然后使用该 ID 更新通知。

startForeground 方法的第一个字段不是标志而是ID。这里是签名:

void startForeground (int id, Notification notification)

文档here

因此您可以使用相同的 ID 更新通知。

mNotificationManager.notify(sNotificationId, notification);