我正在使用ListenableWorker执行后台任务。我也希望OS知道我的服务重要性,所以我打电话给
setForegroundAsync(new ForegroundInfo(WorkerConstants.NOTIFICATION_FOREGROUND_ID,
builder.build()));
按照google文档中的建议。
但是,当我的服务停止或取消时,我仍然可以看到前台服务通知,并且无法删除它。
此外,我在此通知中添加了取消按钮,但是它什么也没做,我无法将其关闭:
PendingIntent intent = WorkManager.getInstance(getApplicationContext())
.createCancelPendingIntent(getId());
builder.addAction(R.drawable.ic_redesign_exit,"Stop",intent);
有什么建议吗?
Context context = getApplicationContext();
String title = context.getString(R.string.str_synchronisation);
String cancel = context.getString(R.string.str_cancel_synchronisation);
// This PendingIntent can be used to cancel the worker
PendingIntent intent = WorkManager.getInstance(context)
.createCancelPendingIntent(getId());
//notificationManager.cancel(notification_ID);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, notif_ch_id)
.setSmallIcon(R.drawable.ic_sync_black_24dp)
.setContentTitle(title)
.setContentText("Use this Content")
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// // Add the cancel action to the notification which can
// // be used to cancel the worker
.addAction(android.R.drawable.ic_delete, cancel, intent);
notificationManager.notify(notification_ID, builder.build());
不要忘记保留通知管理器的实例:
notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
通过以下方式更新您的通知:
builder.setContentText(context.getString(R.string.str_veuiller_patienter)
+ ", fichier " + String.valueOf(i + 1) + totalfiles);
notificationManager.notify(notification_ID, builder.build());
取消您的通知:
notificationManager.cancel(notification_ID);