Before reading this article, please go through the following article,
In this article we will see through code how to implement the Background Task.
Background Task: Windows Runtime Component
- File -> Windows -> Universal -> Windows Runtime Component (Universal Windows),
Add interface IBackgroundTask and implement the Run method and Canceled event.
Main Application
Create New Project -> Blank App (Universal Windows) (I have used the same solution.)
Package.appxmanifest
Open the Package.appxmanifest -> Declarations-> Available Declarations -> Select & Add-> Background Tasks.
Select which background task should support your app (for this example I used the System event).
And App settings -> Add the Entry point -> BGProcess.BgTask (Windows Runtime Component Namespace.classname),
Add Windows Runtime class as a Reference
Implement Background Task into Main Project
Before creating Background task first check whether BackgroundExecutionManager app has required permission or not.
Check whether Background is registered or not.
If App has permission check if task is registered already or not.
BackgroundTaskRegistration class, check whether task already is registered or not. If register returns the BackgroundTaskObject, Check with Background Task Name,
If not registered create BackgroundTaskBuilder & register into the BackgroundTaskRegistration class.
Create BackgroundTaskBuilder Object
To create BackgroundTask object Name and TaskEntryPoint must be specified.
Task Name (Name of the BG task name) and Task Entry Name: Windows Runtime component (Namespace with Class Name),
Define the Trigger when the background task should run and add the condition to raise the event (this is optional),
And register into the BackgroundTaskRegistration Manager,
Complete function
Implement callback to receive the input from Background to trigger the event
UI Design to test BG Task.
Xaml coding
Same Code behind page
- private void BtnBgStart_OnClick(object sender, RoutedEventArgs e)
- {
- BackgroundTask = HandlingBgTask.CreateBgTask(_bgTaskName, "BGProcess.BgTask");
- if (BackgroundTask == null) return;
- BackgroundTask.Completed += _backgroundTask_Completed;
- BackgroundTask.Progress += _backgroundTask_Progress;
- ActiveStatus = true;
- TxtStatus.Text = "Name : " + BackgroundTask.Name;
-
- StatusUpdate = "Waiting for Background event";
- }
- private async void _backgroundTask_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args) {
- await Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
- {
- StatusUpdate = "Get Alert from BG Process :" + sender.Name;
- ActiveStatus = false;
- });
- }
Go to settings -> Time & language -> Date & Time and change time zone background task to trigger the changed event,
- Before Change,
- After change,
Note: When time zone events are triggered only the time is different.