我正在通过以下代码启动用于位置监控的前台服务。
string content = "Tracking started. You can change the tracking settings...";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.SetDefaults((int)NotificationDefaults.All)
.SetSmallIcon(Resource.Drawable.notification)
.SetVibrate(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })
.SetSound(null)
.SetChannelId(NOTIFICATION_CHANNEL_ID)
.SetPriority(NotificationCompat.PriorityDefault)
.SetAutoCancel(true)
.SetContentTitle("Smart Office")
.SetContentText(content)
.SetOngoing(false);
StartForeground(NOTIFICATION_SERVICE_ID, builder.Build(), Android.Content.PM.ForegroundService.TypeLocation);
此通知不会因为滑动或点击而消失,因为它是前台服务并且没有意图,这正是我想要的。
然后,当用户进入某个区域时,我使用 SetAutoCancel(true) 和 SetContentIntent(pendingIntent) 创建一个通知,如下所示。
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent);
Notification.Builder notificationBuilder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.notification)
.SetContentTitle("Smart Office")
.SetContentText(message)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.SetOngoing(false);
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(NOTIFICATION_SERVICE_ID, notificationBuilder.Build());
现在我希望通过滑动或单击通知来消失此通知。单击时,它会打开正确的意图,但通知不会消失。这是什么原因呢?
注意:如果我在启动前台服务之前(即在 StartForeground(NOTIFICATION_SERVICE_ID, builder.Build(), Android.Content.PM.ForegroundService.TypeLocation); 之前显示此通知,那么我可以将通知刷走。
提前致谢。
我必须更改 Notify 方法中的 id。我更改了 notificationManager.Notify(NOTIFICATION_SERVICE_ID, notificationBuilder.Build());到 notificationManager.Notify(NOTIFICATION_ALARM_ID, notificationBuilder.Build());它显示了两个通知。