作爲我的任務的一部分我想刪除已經收到但未在一定時間後與之互動的通知。這意味着如果在此時間後通知仍在通知欄中,應用程序將自動刪除該通知。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狀態時通過執行代碼來看到部分解決方案,但是當應用程序從未打開時仍然無法刪除通知。
任何建議,非常感謝!