简体   繁体   中英

Get String Windows Phone 8.1 through Background Task

I've finally got a background task working which can send Toast notifications to the foregroud. Unfortunately, I've run into an issue. My background task needs to check an rss feed for updates, but when I run

HttpClient hc = new HttpClient();
string result = await hc.GetString("http://url.com");

Nothing happens after the GetString method is fired, not returns, it never jumps to the next line. I've also tried with BackgroundDownload and it's also just stopping like httpclient, when it's supposed to download?

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

I've looked every where for answer to this, but I cannot seem to find one... So how do I get the string from a site, like I would with hc.GetString(""); ?

This is my code:

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

My guess is that the background task is terminating because of the async call to hc.GetString()

You can fix this by requesting a BackgroundTaskDeferral - see step 4 in this quickstart about background tasks for a code example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM