Search code examples
c#.netwindows-phone-8.1background-task

Program Terminates when Background Event Fire


I have made a Background Taks demo. It is a 95% % copy of the SOLUTION in this Question: Windows Phone 8.1 Background Task - Can't Debug and won't fire

The complete example OF THE SOLUTION can be download here : http://1drv.ms/1qCPLMY

The problem is when my event fires the program terminates. "my" solution can be downloaded here: http://1drv.ms/1x3z7Mp

So here is "my" code :

First the class implementing IBackgroundTask

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;

namespace Tasks
{
    public sealed class Upload : IBackgroundTask
    {
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Hello IBackgroundTask");
            //return;
            var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
            var textElements = toastXml.GetElementsByTagName("text");

            var networkStateChangeEventDetails = (taskInstance.TriggerDetails as Windows.Networking.Connectivity.NetworkStateChangeEventDetails);
            if (networkStateChangeEventDetails == null)
                return;

            textElements[0].AppendChild(toastXml.CreateTextNode("I'm message from your task!"));
            ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
        }
    }
}

And here is the code for registering the Background taks:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    Debug.WriteLine("Registering task");
    var taskRegistered = false;
    var exampleTaskName = "UploadTask";

    foreach (var task in BackgroundTaskRegistration.AllTasks)
    {
        if (task.Value.Name == exampleTaskName)
        {
            //taskRegistered = true;
            task.Value.Unregister(true);
            //   break;
        }
    }


    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.NetworkStateChange, false));
        BackgroundTaskRegistration task = builder.Register();
        //task.Completed += new BackgroundTaskCompletedEventHandler(NetworkStateChangeTaskOnCompleted);
        //task.Trigger += new BackgroundTaskCompletedEventHandler(NetworkStateChangeTaskOnCompleted);

                        await new MessageDialog("Task registered!").ShowAsync();
    }
}

private void NetworkStateChangeTaskOnCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
    var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
    var textElements = toastXml.GetElementsByTagName("text");

    textElements[0].AppendChild(toastXml.CreateTextNode("NetworkStateChangeTaskOnCompleted() =>"));
    textElements[0].AppendChild(toastXml.CreateTextNode("I'm message from your task!"));

    ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
}

I get no exception, and no error mesage. The program just terminates, when the event fires. Same on both Device and Emulator.


Solution

  • I've checked your project there are couple of things you need to improve:

    • first and most important - your BackgroundTask must be a Windows Runtime Componenet not a Class library (as it is now) - open properties of the Background Task and change it. BackgroundTask must be a runtime component - that's why your program terminates.
    • you will also need to change the namespace to the project's (file's) name - in this case you will have Task.Upload (instead of Tasks.Upload). Remember also to change entry in Declarations in package.appxmanifest file.

    As I've tried after this changes your app should work fine.