Search code examples
androidandroid-notificationsandroid-workmanager

ListenableWorker does not remove notification icon


I am using ListenableWorker to perform background tasks. Also I want OS to be aware of my service importance, so I call

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

As suggested in the google documentation.

But when my service stopped or cancelled, i can still see foreground service notification and i cannot remove it.

Furthermore, I added cancel button to this notification, but it does nothing, I cannot close it:

PendingIntent intent = WorkManager.getInstance(getApplicationContext())
                            .createCancelPendingIntent(getId());
                    builder.addAction(R.drawable.ic_redesign_exit,"Stop",intent);

Any suggestions?


Solution

  • I filed an issue to google tracker with this. And found out that was totally worng.

    Official response as follows:

    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);
    }