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()將始終被觸發,而不管應用程序的狀態如何。我意識到的計時器將在前景,背景和應用程序關閉狀態下觸發。唯一不行的是應用程序被強制停止,但在我的情況下,這不會導致問題。