我终于得到了一个后台任务,可以将Toast通知发送到foregroud。不幸的是,我遇到了一个问题。我的后台任务需要检查rss提要以获取更新,但是当我运行时
HttpClient hc = new HttpClient();
string result = await hc.GetString("http://url.com");
触发GetString方法后没有任何反应,没有返回,它从不跳转到下一行。我还尝试使用BackgroundDownload
,它还会像httpclient一样停止,当它应该下载时?
StorageFolder folder = ApplicationData.Current.TemporaryFolder;
StorageFile file = await folder.CreateFileAsync("feed.txt");
BackgroundDownloader test = new BackgroundDownloader();
DownloadOperation operation = test.CreateDownload(new Uri("https://url.com"), file);
operation.Priority = BackgroundTransferPriority.Default;
await operation.StartAsync();
我已经找到了解决这个问题的所有方法,但我似乎无法找到一个......那么如何从网站获取字符串,就像我使用hc.GetString("");
一样?
这是我的代码:
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
int lastSeenNews = Convert.ToInt32(Settings.GetValue("lastNews"));
int lastNews = 0;
HttpClient hc = new HttpClient();
var rss = await hc.GetStringAsync("https://url.com");
List<RSSItem> items = new List<RSSItem>();
lastNews = items[0].id;
if (lastSeenNews < lastNews)
{
int unreadNotifications = 0;
List<RSSItem> unreadStatuses = items.Where(x => x.id > lastSeenNews).ToList();
unreadNotifications = unreadStatuses.Count;
}
ToastTemplateType toastTemplate = ToastTemplateType.ToastText01;
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
toastTextElements[0].AppendChild(toastXml.CreateTextNode(Settings.GetValue("lastNews")));
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
deferral.Complete();
}
答案 0 :(得分:1)
我的猜测是后台任务因为对hc.GetString()
您可以通过请求BackgroundTaskDeferral
来解决此问题 - 请参阅this quickstart about background tasks中的第4步以获取代码示例。