android - ListenableWorker 不移除通知图标

标签 android android-notifications android-workmanager

我正在使用 ListenableWorker 来执行后台任务。
另外我希望操作系统知道我的服务重要性,所以我调用

 setForegroundAsync(new ForegroundInfo(WorkerConstants.NOTIFICATION_FOREGROUND_ID,
 builder.build()));

正如谷歌文档中所建议的那样。

但是当我的服务停止或取消时,我仍然可以看到前台服务通知,我无法删除它。

此外,我在此通知中添加了取消按钮,但它什么也没做,我无法关闭它:
PendingIntent intent = WorkManager.getInstance(getApplicationContext())
                            .createCancelPendingIntent(getId());
                    builder.addAction(R.drawable.ic_redesign_exit,"Stop",intent);

有什么建议么?

最佳答案

我用这个向谷歌跟踪器提交了一个问题。并发现那是完全破旧的。

官方回复如下:

Looking at your sample app, you are introducing a race between completion of your ListenableFuture returned by CallbackToFutureAdaptor, and the main looper.

Even without the use of REPLACE one of your Notification updates is posted after your Worker is marked as successful.

However, you can actually avoid the race condition by waiting for the call to setForegroundAsync() to be completed (because that also returns a ListenableFuture). Once you do that - you never have a notification that shows up after your Worker is done.

I will also go ahead and file an improvement on how we can automatically do this even when developers get this wrong.


try {
    // This ensures that you waiting for the Notification update to be done.
    setForegroundAsync(createForegroundInfo(0)).get();
} catch (Throwable throwable) {
    // Handle this exception gracefully
    Log.e("FgLW", "Something bad happened", throwable);
}

关于android - ListenableWorker 不移除通知图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60541280/

相关文章:

Android 本地通知有时不会显示

Android 显示通知不起作用

android - worker 经理的自定义约束

android - WorkManager 在其中的异步方法完成之前返回结果

android - 使用 WorkManager 安排重复工作时出现 IllegalStateException

java - 如何将用户输入的语音命令与硬编码字符串进行比较

java - 如何动态引用 XML id 来播放声音

Android:仅在离开应用程序时显示状态栏通知

android - 从 preferenceScreen Android 打开 WebView 而不是浏览器

java - 无法找到方法“com.google.common.base.Preconditions.checkState”