Your application, even in its inactive state, can react to events generated by the system. To do this, you must register the background job using the SystemTrigger class.
For example, you can “catch” the event of the appearance of the Internet, receiving SMS, changing the time zone or some other.
')
In addition to this, you can add a check for compliance of the state of the device / system with certain conditions. In case of triggering, all specified conditions will be checked.
In addition to system triggers, there are various other triggers that can be triggered by a timer or as a result of special events.
So, I list the possible types of triggers that are used in Windows 8.1 applications:
SystemTrigger - The most popular trigger. Fires if a system event occurs.
Triggers that do not require registration on the lock screen are:
InternetAvailable - the background task runs when the Internet becomes available.
NetworkStateChange - the background task is launched when the network state changes
OnlineIdConnectedStateChange - the background task is launched when the Microsoft account connected to this account is changed
SmsReceived - background task starts when a new SMS is received
TimeZoneChange - background task starts when the time zone on the device changes
ServicingComplete - background task starts when the system completes the application update
If the application is registered on the lock screen, the following triggers are also available:
UserPresent - the background task is started when the user returns
UserAway - the background task runs when the user is idle
ControlChannelReset - the background task starts when the control channel is cleared
SessionConnected - the background task is started when the session is connected
BackgroundWorkCostChange - the background task is activated when the assessment of the background work changes
If you use these triggers without registering on the lock screen, then the registration line for the background job
BackgroundTaskRegistration task = bgTaskBuilder.Register();
will cause an access denied exception.
In order to react to the events of the registration of the application on the lock screen, there are 2 more triggers:
LockScreenApplicationAdded - background task starts when a tile is added to the lock screen
LockScreenApplicationRemoved - the background task starts when the tile is removed from the lock screen
In Windows 10, a new system trigger was introduced:
PowerStateChange - background task starts when battery status changes
System triggers are over, consider other available triggers.
MaintenanceTrigger - The easiest and coolest trigger. Works like a timer. You set your own interval, which must be at least 15 minutes and, if the PC is connected to AC power, the trigger will work. What is good is the fact that this trigger does not require registration of the application on the lock screen! All that is required is that the PC must be plugged in.
If the
FreshnessTime interval time is set to a value less than 15 minutes, then an attempt will be thrown when attempting to register a trigger.
TimeTrigger is almost the same as MaintenanceTrigger, but does not require power from the network, but it requires registration of the application on the lock screen.
PushNotificationTrigger - can be used to receive raw notifications. Requires registration of the application on the lock screen.
ControlChannelTrigger - for specialized networking capabilities. Requires registration of the application on the lock screen.
DeviceUseTrigger - provides access to sensors and peripherals in the background. Unlike other triggers, it is executed only if the application is suspended. Does not support execution conditions.
Conditions - Performance ConditionsWhen a trigger is triggered, you can check the following conditions:
InternetAvailable / InternetNotAvailable
SessionConnected / SessionDisconnected
UserNotPresent / UserPresent
With the release of Windows 10 triggers significantly increased. A complete list can be found among the classes.
Windows.ApplicationModel.BackgroundHere are some new triggers that have become available in Windows UAP applications:
ApplicationTrigger - with the help of this trigger, you can start the execution of background task from anywhere in the code (at the touch of a button, for example)
ToastNotificationActionTrigger - occurs when the user
performs an action with toast notifications
ToastNotificationHistoryChangedTrigger - Allows you to track changes to the history of notifications. It can be used, for example, in order to “catch” the moment of clearing messages in the notification center.
LocationTrigger - a location change event that triggers a background job (used for Geofencing)
DeviceServicingTrigger - an event that is triggered during a long update operation (firmware or parameters) of the device
DeviceWatcherTrigger - happens when some changes happen with the list of connected devices
Below is just a list of the remaining new triggers (there are a lot of them, right?):
AppointmentStoreNotificationTrigger
ActivitySensorTrigger
BluetoothLEAdvertisingPublisherTrigger
BluetoothLEAdvertisingWatcherTrigger
CachedFileUpdaterTrigger
ChatMessageNotificationTrigger
ChatMessageReceivedNotificationTrigger
CommunicationBlockingAppSetAsActiveTrigger
ContactStoreNotificationTrigger
ContentPrefetchTrigger
DeviceConnectionChangeTrigger
DeviceManufacturerNotificationTrigger
EmailStoreNotificationTrigger
GattCharacteristicNotificationTrigger
MediaProcessingTrigger
MobileBroadbandDeviceServiceNotificationTrigger
MobileBroadbandPinLockStateChangeTrigger
MobileBroadbandRadioStateChangeTrigger
MobileBroadbandRegistrationStateChangeTrigger
NetworkOperatorNotificationTrigger
NetworkOperatorHotspotAuthenticationTrigger
Phonetrigger
RcsEndUserMessageAvailableTrigger
RfcommConnectionTrigger
SmartCardTrigger
SmsMessageReceivedTrigger
StorageLibraryContentChangedTrigger
SocketActivityTriggerApparently, some triggers do not work under certain conditions, and are designed to run background tasks with a specific goal. Take, for example, the
MediaProcessingTrigger trigger - as described, it allows an application to transcode multimedia as part of a background task. Thanks to this, the transcoding can continue even when the foreground application has completed its work.
If an application registers a background job, then it is necessary that this feature be documented in the manifest. This can be done simply by using the manifest graphical editor:


In case you need to register several background tasks, add as many tasks as you need in the graphical editor of the manifest:

Or, you can manually open the manifest with any XML editor and add a similar construct inside the Application tag:
<Extensions> <Extension Category="windows.backgroundTasks" EntryPoint="BGTaskMD.ExampleBackgroundTask"> <BackgroundTasks> <Task Type="timer" /> </BackgroundTasks> </Extension> <Extension Category="windows.backgroundTasks" EntryPoint="BGTaskMD.AppUpdateServicingCompleteTask"> <BackgroundTasks> <Task Type="systemEvent" /> </BackgroundTasks> </Extension>
A Windows 8.1 application can automatically register itself on the lock screen using:
BackgroundAccessStatus accessresult = await BackgroundExecutionManager.RequestAccessAsync();
as a result, the user will be prompted to add the App on the Lock Screen.
This method returns a
BackgroundAccessStatus enumeration.
Windows 10 and Windows Phone 8.1 applications do not require registration on the lock screen, but calling RequestAccessAsync before registering a Task is mandatory for them.
There are 2 options for registering the application on the lock screen - the badge and badgeAndTileText. Only badge and badge with text. The option can be selected both through the graphic editor of the manifest, and through editing the XML code. In addition to the choice of options, you must specify a badge image - BadgeLogo:
<uap:VisualElements DisplayName="Background Task example" Square150x150Logo="Assets\Square150x150Logo.png" Square44x44Logo="Assets\Square44x44Logo.png" Description="BGTaskExample" BackgroundColor="transparent"> <uap:LockScreen Notification="badgeAndTileText" BadgeLogo="Assets\BadgeLogo.png" /> <uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png" ShortName="Background Task example"> </uap:DefaultTile> <uap:SplashScreen Image="Assets\SplashScreen.png" /> </uap:VisualElements>
Through the graphical editor of the manifest, of course, it is more convenient to do this:


In order for the application to register on the lock screen in the badgeAndTileText mode, you need to check that it also has a picture for a wide tile - WideLogo.
The application can display various information on the lock screen, such as: badge, text from the last tile notification, toast notification. No special action is required for this.
A maximum of 7 applications can be registered on the lock screen. And only one of them can display a wide tile.
Applications that are registered on the lock screen have more privileges in relation to other applications. They can use more resources.
Limits on the use of resources are necessary so that the user's device does not “catch the brakes” from constantly running tasks in the background and does not put the battery on.
For example:
If the application is registered on the lock screen, it can use 2 seconds of CPU time every 15 minutes.
If the application is not registered on the lock screen, then it can only use one second of CPU time every 2 hours.
If this app is for Windows Phone, then it can use 2 seconds every 15 minutes.
If the device is not connected to AC power, but is powered by a battery, the quota for using network data is automatically turned on (to save the amount of energy consumed by the network interface).
In Windows Phone, when the battery saving feature is on, background tasks will not start if the device is not connected to an external power source and the battery charge is less than a certain level.
More details on the link:
Application support using background tasks (XAML)After updating the application, it is necessary to update the background task (unregister and re-register). The “ServicingComplete trigger” mentioned earlier will help us “catch” the moment of the application update. Use this trigger complies with the rules of good tone (almost must use).
You can check out this way:
foreach (var _task in BackgroundTaskRegistration.AllTasks) { if (_task.Value.Name == "My demo task") { _task.Value.Unregister(true); } }
If the value of the Unregister method is true, then all currently running instances of the background task will be canceled. If set to false, then tasks will be given the opportunity to complete their work.
By the way, even after restarting the computer, the triggers are still working.
When the trigger is initialized, the second parameter is the so-called OneShot parameter, which indicates whether the trigger will be executed only once or many times. For example:
SystemTrigger taskTrigger = new SystemTrigger(SystemTriggerType.ServicingComplete,false);
A little guide to action.Create a project like Blank App (Universal Windows)
We add another project of the Windows Runtime Component (Universal Windows) type to the solution.
In the first draft, add a link to the second. You can do it like this:
in Solution Explorer, on the project name, we call the context menu, select Add / Add - then Reference ... / Link ... and in the window, select Projects / Projects and put a check mark next to our second project

In this file, the class code of the background job should be something like this:
public sealed class ExampleBackgroundTask : IBackgroundTask { public void Run(IBackgroundTaskInstance taskInstance) {
Add a namespace:
using Windows.ApplicationModel.Background;
Before registering, it is necessary to check whether the trigger is already registered, otherwise we will receive a set of registrations of the same trigger.
foreach (var _task in BackgroundTaskRegistration.AllTasks) { if (_task.Value.Name == "My demo task") { return; } }
If the trigger requires registration on the initial screen, then before registering the trigger, you need to insert a similar snippet:
You can register a trigger like this:
TimeTrigger taskTrigger = new TimeTrigger(15, false); var bgTaskBuilder = new BackgroundTaskBuilder(); bgTaskBuilder.Name = "My demo task"; bgTaskBuilder.TaskEntryPoint = "BGTaskMD.ExampleBackgroundTask"; bgTaskBuilder.SetTrigger(taskTrigger);
The Completed event occurs if the application is currently running. If the application is suspended (suspended) and then terminated, the event does not occur. If the application is paused and then resumed, then Completed is triggered after resuming.
In addition to Completed, you also need to handle the cancellation of the background task - Canceled. But it is not processed when registering a task, but when it is implemented, that is, in the class of our WinMD file.
public sealed class ExampleBackgroundTask : IBackgroundTask { volatile bool _cancelRequested = false; public void Run(IBackgroundTaskInstance taskInstance) { taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
If an asynchronous code is executed during a background task, in order for the code to terminate correctly if the application is interrupted, defferal must be used. In this case, the Run method would get something like this:
public void Run(IBackgroundTaskInstance taskInstance) { BackgroundTaskDeferral _deferral = taskInstance.GetDeferral(); await someAsyncTask(); _deferral.Complete(); }
It is recommended to write short tasks that do not interfere with the operation of the system.
While the background task is running, you can write process status values ​​to settings — Windows.Storage.ApplicationData.Current.LocalSettings and read them if necessary.
User interaction in background tasks is not used. No user interface elements, except for notifications, tiles and updates of the event indicators from the background task code, are not recommended.
Debugging the background task runs the risk of becoming a tedious task if you perform an event triggered by a trigger, treyt it or even wait at least 15 minutes for the MaintenanceTrigger or TimeTrigger to work (although some developers probably dream of such debugging).
In order for VS to have the opportunity to call a trigger, the code of our background task must be transferred to the metadata file - WinMD. We did just that, so when debugging we can see our background task in the events of the application life cycle.

In order for this to work, the background task must already be registered and wait for the launch.
If you register the background task with the OneShot parameter, then after it works, the debugging of the task through Visual Studio will no longer be available.
Debugging via Visual Studio is not available for triggers such as ControlChannelTrigger, PushNotificationTrigger, as well as for background tasks using SystemTrigger with trigger type SmsReceived.
My example of implementing TimeTrigger and ServicingComplete can be found on
GitHubAs for working with the Internet, the background tasks are not intended for downloading large amounts of data. But they are convenient for something like a news update or event monitoring. If you want to download large files, you need to use the
BackgroundDownloader class.
Consider a simple example of loading data:
using Windows.Networking.BackgroundTransfer; using Windows.Storage;
Finally, and even so removed from the topic, I will add that for short-term operations involving the downloading of small resources, you can or even need to use the
Windows.Web.Http namespace
var uri = new Uri("http://habrahabr.ru/post/264199/"); var httpClient = new HttpClient(); try