New BackgroundTask Triggers in Windows 10

In the Windows 10 developer preview there are some new background triggers that can be very useful for number of scenario's. I will make a couple of blogposts of which triggers I found.

Let start with the first: ApplicationTrigger. It's a common question I see at MSDN. How can the app itself trigger the background task. the awnser, it can't. Windows 8 apps cant trigger the background task on demand. With Windows 10 this is changing. We are now able to trigger the backgroundtask from the foreground. How it works?

First create a background task for test purpose: - create a Windows Runtime Component as you did in Windows 8 app - create a new class and make a background task implementation. I have this

public sealed class MyBackgroundTask : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance)
    {

    }
}

to see it works i set a breakpoint in the run method. You can also write some code ofcourse. Make also a reference from your app the the winrt component.

Second step is to register your BackgroundTask in the manifest. Since the designer seems to be broken you need to add this xml yourself:

<Extensions>
    <Extension Category="windows.backgroundTasks" EntryPoint="RTLibrary.MyBackgroundTask">
      <BackgroundTasks>
        <Task Type="general" />
      </BackgroundTasks>
    </Extension>
  </Extensions>

It have to be a child of the Application element that is already in the xml.

Third step is to make the trigger. You will need to keep a reference to this trigger so you can invoke it when you want run the task.

private readonly ApplicationTrigger _trigger;

public MainPage()
{
    this.InitializeComponent();

    _trigger = new ApplicationTrigger();
}

After created the trigger you need to register the background task. this is something you should be familiar with.

protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            foreach (var t in BackgroundTaskRegistration.AllTasks)
                t.Value.Unregister(true);

            BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
            builder.TaskEntryPoint = "RTLibrary.MyBackgroundTask";
            builder.Name = "AppTrigger";
            builder.SetTrigger(_trigger);
            var registration = builder.Register();
        }

Now for test purpose add a button to your UI and implement the click handler. When the button is clicked we going to trigger the background task. To do this you only need one more line of code. Just call the RequestAysnc method of the trigger:

private async void Button_Click(object sender, RoutedEventArgs e)
        {
            await _trigger.RequestAsync();
        }

Another new trigger is the ToastNotificationHistoryChangedTrigger. When you use this trigger your backgroundtask gets invoked when the user dismisses the toast notification from the notification center. This can be useful to update the Tile for example.

To use this, we keep the code from above. Just going to add a few things. First we change the trigger of the background task registration:

foreach (var t in BackgroundTaskRegistration.AllTasks)
    t.Value.Unregister(true);

BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
builder.TaskEntryPoint = "RTLibrary.MyBackgroundTask";
builder.Name = "AppTrigger";
builder.SetTrigger(new ToastNotificationHistoryChangedTrigger());
var registration = builder.Register();

As you see only changed the Trigger. Below this we add some test code to add a notification to the notification center:

var toastUpdates = ToastNotificationManager.CreateToastNotifier();
var template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);

template.GetElementsByTagName("text")[0].InnerText = "Test Notification";

toastUpdates.Show(new ToastNotification(template));

Now we need to add something to the manifest. TO the uap:Application element add this attribute: ToastCapable="true"

Now run the application, make sure you have a breakpoint in the background task. You see for a moment the toast notification. Now open the notification center and swipe the notification away. A few seconds after your breakpoint in your notification gets hit!

Now there is some more information. The triggerdetails contains more information about what kind of change the user maked:

var details = taskInstance.TriggerDetails as ToastNotificationHistoryChangedTriggerDetail;
if (details != null)
{
    switch(details.ChangeType)
    {
        case ToastHistoryChangedType.Added:
            break;
        case ToastHistoryChangedType.Cleared:
            break;
        case ToastHistoryChangedType.Expired:
            break;
        case ToastHistoryChangedType.Removed:
            break;
    }
}
  •   @JenMsft never mind; i found it by going to the old control panel; made a feedback item for it https://t.co/WmouYyriYV
  •   @peterskillman need help testing? :)
  •   @JenMsft i had to reset windows (recovery in the settings app) on my surface book 2 in order to be able to get a fi… https://t.co/0oTMC6nvpb
  •   RT @WBuzzer: Microsoft and Amazon Finally Launch Cortana and Alexa Integration https://t.co/8yJ1ijZRoU https://t.co/K24wtKFkSA
  •   @tfsbuck @thomsen_digital @cschleiden @matthewisabel +1 extension builders need guidiness for this. and what is the… https://t.co/3Ecj7tEkPG
  •   RT @rajen_k: Visual Studio 2017 version 15.8 is now available for download! Check out the details at https://t.co/G23ibMjjfY #VisualStudio
  •   @ingnl laatste windows 10; en ook op laatste insider build geprobeerd maar niet veel beter; Dus terug naar de vraag… https://t.co/zK70bdkiaM
  •   @Rabobank doe ik het voor jullie; gister de website omgezet :)
  •   @Rabobank nee gewoon voor mijn laptop
  •   @Rabobank een app? of zal ik mijn versie maar publiseren? https://t.co/ooJT7dJFQP