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