Windows Phone 8.1 Background Task - Can't Debug and won't fire

心不动则不痛 提交于 2019-11-29 08:43:34

As I've tried your code, there is a problem with this specific SystemTriggerType.NetworkStateChange - indeed I also don't see the registered BackgroundTask in Lifecycle Events dropdown. But if I only change the SystemTriggerType for example to SystemTriggerType.TimeZoneChange then I'm able to see it.

Here is the code modified a little:

await BackgroundExecutionManager.RequestAccessAsync();
if (!taskRegistered)
{
    Debug.WriteLine("Registering task inside");
    var builder = new BackgroundTaskBuilder();
    builder.Name = exampleTaskName;
    builder.TaskEntryPoint = "Tasks.Upload";
    builder.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false));
    BackgroundTaskRegistration task = builder.Register();
    await new MessageDialog("Task registered!").ShowAsync();
}

I'm not sure why with the original code the BackgroundTask is not visible in VS, though it is being registered - it's in BackgroundTaskRegistration.AllTasks - in this case maybe try to debug with different SystemTriggerType and swich to desired one with release version.

I've also tested if the BackgroundTask with the problematic SystemTriggerType.NetworkStateChange works - and indeed - it is working. I've modified your BackgroundTask a little to send a toast message when NetworkState changes. After registering the task, when I turn the WiFi on/off, I get a toast messgae. The code for the task:

public sealed class Upload : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        Debug.WriteLine("Hello Pat");
        ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
        XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
        XmlNodeList textElements = toastXml.GetElementsByTagName("text");
        textElements[0].AppendChild(toastXml.CreateTextNode("Upload Task - Yeah"));
        textElements[1].AppendChild(toastXml.CreateTextNode("I'm message from your Upload task!"));
        ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
    }
}

The complete example you can download here.

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