嗨,我的要求是我想从 APi 读取数据,如果数据可用,我想发送本地通知,否则不发送本地通知。即使应用程序处于关闭状态或后台。
public static void ScheduleLocalNotifications()
{
// Request permission to display alerts and play sounds.
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound, async (granted, error) =>
{
if (granted)
{
//NotificationsData data = await GlobalParams.ReadNotification();
int rem = new Random().Next(1, 100);
//foreach (var item in data.resultnew)
//{
string StatusTxt = string.Empty;
// Your notification content
var content = new UNMutableNotificationContent
{
Title = "Activated",
Body = "Next No: "+rem,
Sound = UNNotificationSound.Default
};
// Trigger to repeat every 5 minutes
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(120, true);
// Create a notification request
var request = UNNotificationRequest.FromIdentifier("FiveMinuteNotification", content, trigger);
// Schedule the notification
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
{
if (err != null)
{
//Console.WriteLine($"Error scheduling notification: {err.LocalizedDescription}");
}
});
//}
}
else
{
}
});
}
我尝试了上面的代码,但每次发送相同的消息时它都没有更新通知消息
我使用你的代码来推送通知。具体来说,将
ScheduleLocalNotifications()
方法绑定到按钮的单击事件。点击按钮后,将应用程序置于后台,稍后会收到通知:
notifyButton.Clicked += (sender, e) =>
{
ScheduleLocalNotifications();
};
您收不到的原因可能是您设置的通知推送间隔太长(120表示120秒,可能您在收到通知之前急于关闭程序)。建议您尝试设置较短的时间间隔,或者耐心等待两分钟