作为我的任务的一部分我想删除已经收到但未在一定时间后与之互动的通知。这意味着如果在此时间后通知仍在通知栏中,应用程序将自动删除该通知。Xamarin Android在一定时间后取消后台通知
对于前景通知这不是问题,因为我施加下面的代码:
void SendNotification(RemoteMessage remotemessage)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
long[] pattern = { 100, 100, 100, 100 };
var notificationBuilder = new Notification.Builder(this)
.SetVibrate(pattern)
.SetSmallIcon(Resource.Drawable.mhu2)
.SetContentTitle(remotemessage.GetNotification().Title)
.SetContentText(remotemessage.GetNotification().Body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager)GetSystemService(Context.NotificationService);
int id = 0;
notificationManager.Notify(id, notificationBuilder.Build());
Handler handler = new Handler(Looper.MainLooper);
long delayInMilliseconds = 5000;
handler.PostDelayed(new Runnable(() => notificationManager.Cancel(id)), delayInMilliseconds);
}
当接收到通知时,它会自动5秒后(调试目的)除去。但是,众所周知,根据应用程序的状态,通知的处理方式不同。
此代码适用于前台应用程序,但在应用程序处于后台或死亡状态时决不会运行。所以当用户在应用程序未打开或在后台收到通知时,通知将不会被删除。
我试着研究这个,并在重写OnDestroy/OnStop/OnPause状态时通过执行代码来看到部分解决方案,但是当应用程序从未打开时仍然无法删除通知。
任何建议,非常感谢!