在创建通知时,设置其自动取消的时间。例如,在通知的 builder 中使用 setAutoCancel(true) 方法,如下所示:
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
// 创建通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId);
builder.setContentTitle("通知标题")
.setContentText("通知正文")
.setSmallIcon(R.drawable.notification_icon)
.setAutoCancel(true); // 设置自动取消
// 显示通知
int notificationId = xxx; // 给通知分配一个唯一 ID
notificationManager.notify(notificationId, builder.build());
// 创建用于取消通知的 PendingIntent
Intent cancelIntent = new Intent(context, YourBroadcastReceiver.class);
cancelIntent.setAction("ACTION_CANCEL_NOTIFICATION");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, cancelIntent, PendingIntent.FLAG_CANCEL_CURRENT);
// 在 WorkRequest 中添加用于取消通知的 PendingIntent
OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(YourWorker.class)
.setInputData(data)
.setInitialDelay(delay, TimeUnit.SECONDS)
.addTag("YOUR_WORK_TAG")
.setConstraints(constraints)
.setBackoffCriteria(backoffDelay, backoffPolicy)
.setInputData(data)
.setCancelationSignal(CancellationSignal().also { it.setOnCancelListener {
// 取消通知
notificationManager.cancel(notificationId)
} })
.build();
WorkManager.getInstance(context).enqueue(request);