Xamarin Android Cancel Task from Notification

不问归期 提交于 2020-03-05 04:23:28

问题


I have a method that will send a user a local notification once per TimeSpan interval:

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);
        }
    }

What I'm shooting for is to have two options on the notification; one will dismiss the current notification, but allow this Task to continue running. The other will cancel this task. Here's the PushNotificationGenerator class:

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());
    }
}

I'm at a loss of what to do to use the CancellationToken from the notification.


回答1:


first in you Push method:

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());
}

in GetVehiclePositionRepeatAsync method:

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);
        }
    }
}

then custom 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();
        }
    }
}

don't forget regist receiver in activiy:

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();
    }


来源:https://stackoverflow.com/questions/57421916/xamarin-android-cancel-task-from-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!