For a Windows 8 App, in C#/Xaml I try to register a background task. It's hard to tell but I guess my background task is well registred but when I click on the name of my background task on the Debug Location Toolbar my app stops working without any message.
I looked at the log on the Event Viewer and I get : "The background task with entry point MyApp.Pages.SampleBackgroundTask and name Example hourly background task failed to activate with error code 0x80010008."
Here is my code :
private async void Button_Click_BackgroundTask(object sender, RoutedEventArgs e)
{
string entryPoint = "MyApp.Pages.SampleBackgroundTask";
string taskName = "Example hourly background task";
TimeTrigger hourlyTrigger = new TimeTrigger(60, false);
BackgroundTaskRegistration myBackGroundTaskRegistration = RegisterBackgroundTask(entryPoint, taskName, hourlyTrigger, null);
if(myBackGroundTaskRegistration != null)
AttachProgressAndCompletedHandlers(myBackGroundTaskRegistration);
}
public static BackgroundTaskRegistration RegisterBackgroundTask(String taskEntryPoint,
String name,
IBackgroundTrigger trigger,
IBackgroundCondition condition)
{
var taskRegistered = false;
var iter = Windows.ApplicationModel.Background.BackgroundTaskRegistration.AllTasks;
foreach (var item in iter)
{
var task = item.Value;
if (task.Name == name)
{
taskRegistered = true;
return item.Value as BackgroundTaskRegistration;
}
}
var builder = new BackgroundTaskBuilder();
builder.Name = name;
builder.TaskEntryPoint = taskEntryPoint;
builder.SetTrigger(trigger);
if (condition != null)
{
builder.AddCondition(condition);
}
BackgroundTaskRegistration taskBack = builder.Register();
return taskBack;
}
private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
{
task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
}
private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
{
var progress = "Progress: " + args.Progress + "%";
}
private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
{
Debug.WriteLine("Hi");
}
I added this in the manifest :
<Extension Category="windows.backgroundTasks" EntryPoint="MyApp.Pages.SampleBackgroundTask">
<BackgroundTasks>
<Task Type="timer" />
</BackgroundTasks>
</Extension>
Did I forget something?
Thank you for your help.
EDIT : here is the code of my Task, within one of my project page :
public sealed class SampleBackgroundTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
_deferral.Complete();
}
}
async
method without anawait
in it, which should be a compiler warning. – Servy