0

作为我的任务的一部分我想删除已经收到但未在一定时间后与之互动的通知。这意味着如果在此时间后通知仍在通知栏中,应用程序将自动删除该通知。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状态时通过执行代码来看到部分解决方案,但是当应用程序从未打开时仍然无法删除通知。

任何建议,非常感谢!

回答

0

我只是想发布一个快速更新,因为我已经能够解决这个问题。

Android根据通知中提供的内容处理不同的通知。我发现如果通知只是用数据域构建的(所以没有通知主体),OnMessageReceived()将始终被触发,而不管应用程序的状态如何。我意识到的计时器将在前景,背景和应用程序关闭状态下触发。唯一不行的是应用程序被强制停止,但在我的情况下,这不会导致问题。