首页 > 解决方案 > 警报管理器本地通知 - 如何取消特定通知?

问题描述

我正在通过警报管理器安排我的客户,以便按时收到我设置的通知。现在一切正常,我收到本地通知,但我无法取消该特定通知,它每分钟后都会出现。

这是我用于取消的视图模型代码 PCL:

void Switch_Toggled()
        {

            if (NotificationONOFF == false)
            {

                MessageText = string.Empty;
                SelectedTime = DateTime.Now.TimeOfDay;
                SelectedDate = DateTime.Today;
                DependencyService.Get<ILocalNotificationService>().Cancel(Convert.ToInt32(Settings.Customerid));
            }
        }

用于保存警报

DependencyService.Get<ILocalNotificationService>().LocalNotification("Local Notification", MessageText, Convert.ToInt32(Settings.Customerid) , selectedDateTime);

xamarin.android 中用于 canel 的代码:

public void Cancel(int id)
        {

            var intent = CreateIntent(id);
            var pendingIntent = PendingIntent.GetBroadcast(Application.Context, Convert.ToInt32(_randomNumber), intent, PendingIntentFlags.Immutable);
            var alarmManager = GetAlarmManager();
            alarmManager.Cancel(pendingIntent);
            var notificationManager = NotificationManagerCompat.From(Application.Context);
            notificationManager.CancelAll();
            notificationManager.Cancel(id);
        }

我正在发送客户 ID 以取消但它不起作用。

标签: xamarin.forms

解决方案


根据您的描述,您有 xamarin.forms 示例,使用警报管理器发送具有重复间隔的本地通知,例如以下示例:

https://www.c-sharpcorner.com/article/how-to-send-local-notification-with-repeat-interval-in-xamarin-forms/

有两种解决方案,但我不知道你是什么。

解决方案1:

当您运行项目并设置一个警报管理器以重复间隔发送本地通知时,此应用程序现在是后台。

当时间到了,你进入这个后台应用,你发现开关没有被选中,但闹钟仍然存在。所以当你进入这个应用程序时,你想取消这个警报,对吗?

如果是,我建议您可以在 LocalNotificationPageViewModel 构造函数中调用 Switch_Toggled() 事件。

public LocalNotificationPageViewModel(){
        SaveCommand = new Command(() => SaveLocalNotification());
        Switch_Toggled();
    }

解决方案2:

如果您运行项目并设置一个警报管理器以重复间隔发送本地通知,并且此应用程序仍然处于活动状态,现在时间到了,您可以取消选择开关以取消此警报,它工作正常。


推荐阅读