Question

I'm trying to register a background task and I'm getting some strange behaviour. I appears that the task itself is registering and firing at the right time; however, when it does fire it's closing my program down (with no error).

I suspect that the reason is linked to the fact that the program is not asking me is I want to allow a background task to run when I launch. I have created a declaration for the background task as a system event, and am registering like this from the App.Xaml.cs:

var builder = new BackgroundTaskBuilder();

builder.Name = "NewTask";
builder.TaskEntryPoint = "ConnectionMonitor.CheckInternet";
builder.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable, false));

BackgroundTaskRegistration task = builder.Register();

So, I believe my question is: why would it not ask me for permission to run a background task (which I assume will give me the answer to my main problem of why it is crashing)?

I'm not sure whether it matters, but this is a Windows Universal app (the app.xaml.cs above is in the Shared project.

The task looks like this:

BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();

bool newConnected = IsConnected();
if (connected != newConnected)
{
    connected = newConnected;
    var notifier = ToastNotificationManager.CreateToastNotifier();
    var template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

    var element = template.GetElementsByTagName("text")[0];
    element.AppendChild(template.CreateTextNode(connected ? "Connection available" : "Connection lost"));

    var toast = new ToastNotification(template);
    notifier.Show(toast);  
}

_deferral.Complete();
Was it helpful?

Solution

You asked: why would it not ask me for permission to run a background task?

The answer is, unless your background task requires lock screen access, it does not require the user's permission to be registered. There is no user prompt, by design. One of the intents of this design is that it allows you to register a task from another task.

In Windows, you do not need to call BackgroundExecutionManager.RequestAccessAsync() except for lock screen access. Calling it will give you more quota but will require the user to approve the task.

In Windows Phone, calling RequestAccessAsync() is required no matter what, but never prompts the user with a UI. For this reason the logic in your Universal App can be shared but will likely have a #if to handle the registration differently, if relevant.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top