Xamarin Android 从通知中取消任务

我有一个方法,可以在每个 TimeSpan 间隔向用户发送一次本地通知:


public async void GetVehiclePositionRepeatAsync(TimeSpan interval, CancellationToken cancellationToken)

    {

        while (true)

        {

            var task = new Task(() => 

            {

                cancellationToken.ThrowIfCancellationRequested();

                var not = new PushNotificationGenerator(this, "Hooray!", "yay", "STOP_NOTIFICATIONS");

                        not.Push();

            });

            task.Start();

            await Task.Delay(interval, cancellationToken);

        }

    }

我的目标是在通知上有两个选项;将消除当前通知,但允许此任务继续运行。对方会取消这个任务。这是 PushNotificationGenerator 类:


public class PushNotificationGenerator

{

    public MapActivity Activity { get; set; }

    public string Title { get; set; }

    public string Text { get; set; }

    public string ChannelId { get; set; }

    public PushNotificationGenerator(MapActivity act, string title, string txt, string channelId)

    {

        Activity = act;

        Title = title;

        Text = txt;

        ChannelId = channelId;

    }


    public void Push()

    {

        var resultIntent = new Intent();

        resultIntent.SetAction("Dismiss");


        var stackBuilder = TaskStackBuilder.Create(Activity);

        stackBuilder.AddParentStack(Class.FromType(typeof(MapActivity)));

        stackBuilder.AddNextIntent(resultIntent);



        var resultPendingIntent = stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);


        var builder = new NotificationCompat.Builder(Activity, ChannelId)

                      .SetAutoCancel(true)

                      .SetContentTitle(Title)

                      .SetSmallIcon(Resource.Drawable.stop_bus)

                      .SetContentText(Text)

                      .AddAction(0, "Dont Dismiss", resultPendingIntent)

                      .AddAction(0, "Dismiss", resultPendingIntent);


        var notificationManager = NotificationManagerCompat.From(Activity);

        notificationManager.Notify(41144, builder.Build());

    }

}

我不知道如何使用通知中的 CancellationToken 。


猛跑小猪
浏览 93回答 1
1回答

Cats萌萌

首先在你的Push方法中:public void Push(){    ...    Intent intentDismiss = new Intent(this, typeof(NotivicationBroadCast));    intentDismiss.SetAction("notification_dismiss");    PendingIntent pendingIntentDismiss = PendingIntent.GetBroadcast(this, 0,    intentDismiss, PendingIntentFlags.UpdateCurrent);    Intent intentCancel = new Intent(this, typeof(NotivicationBroadCast));    intentCancel.SetAction("notification_cancel");    PendingIntent pendingIntentCancel = PendingIntent.GetBroadcast(this, 0,    intentCancel, PendingIntentFlags.UpdateCurrent);    var builder = new NotificationCompat.Builder(Activity, ChannelId)                  .SetAutoCancel(true)                  .SetContentTitle(Title)                  .SetSmallIcon(Resource.Drawable.stop_bus)                  .SetContentText(Text)                  .AddAction(0, "Dont Dismiss", pendingIntentDismiss)                  .AddAction(0, "Dismiss", pendingIntentCancel );    var notificationManager = NotificationManagerCompat.From(Activity);    notificationManager.Notify(41144, builder.Build());}在GetVehiclePositionRepeatAsync方法中:public async void GetVehiclePositionRepeatAsync(TimeSpan interval, CancellationToken cancellationToken){        while (!cancellationToken.IsCancellationRequested) {             var task = new Task(() =>            {                cancellationToken.Token.ThrowIfCancellationRequested();                var not = new PushNotificationGenerator(this, "Hooray!", "yay", "STOP_NOTIFICATIONS");                not.Push();            },cancellationToken.Token);            task.Start();            await Task.Delay(interval);        }    }}然后自定义NotivicationBroadCast:[BroadcastReceiver]class NotivicationBroadCast : BroadcastReceiver{    public override void OnReceive(Context context, Intent intent)    {        string action = intent.Action;        if (action.Equals("notification_dismiss"))        {             NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);                         notificationManager.Cancel(notificationId);        }        if (action.Equals("notification_cancel"))        {                          cancellationToken.Cancel();        }    }}不要忘记在活动中注册接收器:protected override void OnResume()    {        base.OnResume();        NotivicationBroadCast recieve = new NotivicationBroadCast();        IntentFilter intentFilter = new IntentFilter();        intentFilter.AddAction("notification_dismiss");        intentFilter.AddAction("notification_cancel");        RegisterReceiver(recieve, intentFilter);        begin();    }
打开App,查看更多内容
随时随地看视频慕课网APP