Search code examples
uwpwindows-10-mobilebackground-task

Can not handle completed background tasks when application goes to background


I want to do some task(in this case , it is showing toast notification) when received completed event from background task after receive Raw Push Notification. But I have an issue :

When the application runs with debugging, it works normally, the main project can handle completed event from background task and show Toast notification but when I run an application without debugging and goes to background, it does not work, nothing is showed after application receives raw notification.

Here is my code : At main project, I have registered a background task:

    private async void initBackgroundTask()
    {
        string myTaskName = "Ktask";
       var status =  await BackgroundExecutionManager.RequestAccessAsync();
        // check if task is already registered
        foreach (var cur in BackgroundTaskRegistration.AllTasks)
            if (cur.Value.Name == myTaskName)
            {                    
                cur.Value.Unregister(true);
            }
        try
        {
            // register a new task
            BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
            taskBuilder.Name = myTaskName;
            taskBuilder.TaskEntryPoint = typeof(KBackgroundStuff.KBackgroundTask).ToString();
            taskBuilder.SetTrigger(new PushNotificationTrigger());

            //taskBuilder.SetTrigger(new TimeTrigger(15, false));
            BackgroundTaskRegistration myFirstTask = taskBuilder.Register();
            myFirstTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted); ;
            await (new MessageDialog("Task registered")).ShowAsync();
        }
        catch(Exception e)
        {
            Debug.WriteLine("trigger " + e.Message);
        }            
    }

Handle Completed Event from Background Task:

    private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
    {
        // TODO: Add code that deals with background task completion.
        ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
        XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
        XmlNodeList textElements = toastXml.GetElementsByTagName("text");
        textElements[0].AppendChild(toastXml.CreateTextNode("Notification - Yeah"));
        textElements[1].AppendChild(toastXml.CreateTextNode("I'm message from your Notification!"));
        ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));


    }

Background Task:

public sealed class KBackgroundTask : IBackgroundTask
{

    public void Run(IBackgroundTaskInstance taskInstance)
    {
        BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
        RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
        string content = notification.Content;
        System.Diagnostics.Debug.WriteLine(content);            
        _deferral.Complete();
    }


}

Please help my main project can receive completed event from background task when an application runs without debugging . Sorry for my English


Solution

  • The toast notification should not show when your application goes to background. In your code you are sending toast notifications to handle completion events for your background task. However in the Remarks of BackgroundTaskCompletedEventHandler delegate, it has declared that:

    Completion events are delivered only if the task completed while the application is in the foreground. If the application is suspended and then terminated, completion status is not delivered. If the application is suspended and then resumed, it is guaranteed to receive the completion notification.

    When your application goes to background, it will be suspend, so you won't see the toast notification.

    When the application runs with debugging, it works normally, the main project can handle completed event from background task and show Toast notification.

    This is because while debugging with Visual Studio, Visual Studio prevents Windows from suspending an app that is attached to the debugger. This is to allow the user to view the Visual Studio debug UI while the app is running.

    So while debugging, your application actually is always running in the foreground. For more information, please refer to How to trigger suspend, resume, and background events for Windows Store apps in Visual Studio.