Windows Phone came through long way after it’s initial release on Oct 21st 2010. Windows Phone 7.5 update release called as “MANGO” brought lots of improvements including Multi tasking capabilities etc. With the introduction of multi-tasking ( it is not true multi tasking, but an efficient application switching which ensures that only one application will reside in memory and remaining running applications will be in deactivated stage. Since the application is not killed, it can be launched faster – that gives the capability similar to true multi tasking).
What is Background Agents?
Background agents feature allows you to run certain code in a background thread and scheduled tasks are that runs periodically.
Scheduled Tasks and background agents allow an application to execute code in the background, even when the application is not running in the foreground. The different types of Scheduled Tasks are designed for different types of background processing scenarios and therefore have different behaviors and constraints.
Note: that Background agents are not supported in 256MB devices. Only initial 512MB devices with Windows Phone “MANGO” would be able to run background agents
There are types of scheduled tasks or Background Agents and they are:
1. Periodic Task Agents- Periodic task agents will run for a short period of time and does a certain predefined operations defined by you. It also have the capability to run based on certain time interval.
A typical example would be checking whether device is having network connectivity periodically or checking any mails available with mail server etc.
2. Resource Intensive Task Agents- Resource Intensive tasks agents will run for a long period if all your network connectivity(if you need some network processing while doing the task) and power and resource usage etc.
A Typical example of scenario would be your phone receiving some application data updates and additional feature set update etc.
Using Background Agents:
1. To start with Scheduled tasks agents are part of Microsoft.Phone.Scheduler namespace
2. Create a new Windows Phone Scheduled Task project in your Windows Phone solution
3. Click on “OK” and Now I created a Windows Phone Scheduled Task project called “ScheduledTaskAgent1”
and this is how the initial code generated by Visual Studio will appear
using System.Windows; using Microsoft.Phone.Scheduler; namespace ScheduledTaskAgent1 { public class ScheduledAgent : ScheduledTaskAgent { private static volatile bool _classInitialized; /// <remarks> /// ScheduledAgent constructor, initializes the UnhandledException handler /// </remarks> public ScheduledAgent() { if (!_classInitialized) { _classInitialized = true; // Subscribe to the managed exception handler Deployment.Current.Dispatcher.BeginInvoke(delegate { Application.Current.UnhandledException += ScheduledAgent_UnhandledException; }); } } /// Code to execute on Unhandled Exceptions private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { if (System.Diagnostics.Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger System.Diagnostics.Debugger.Break(); } } /// <summary> /// Agent that runs a scheduled task /// </summary> /// <param name="task"> /// The invoked task /// </param> /// <remarks> /// This method is called when a periodic or resource intensive task is invoked /// </remarks> protected override void OnInvoke(ScheduledTask task) { //TODO: Add code to perform your task in background NotifyComplete(); } } }
Now you can see there is an OnInvoke(ScheduledTask task) method, inside that method we will define our Periodic or Resource Intensive tasks implementation.
4. Now it is the time for us to do our implementation. (This sample I have taken from MSDN Reference on How to: Implement Background Agents for Windows Phone)
a.) Scheduled Task Code Implementation (this code will send toast messages, so that you can see that when your application is running in background. )
/// <summary> /// Agent that runs a scheduled task /// </summary> /// <param name="task"> /// The invoked task /// </param> /// <remarks> /// This method is called when a periodic or resource intensive task is invoked /// </remarks> protected override void OnInvoke(ScheduledTask task) { //TODO: Add code to perform your task in background string toastMessage = ""; // If your application uses both PeriodicTask and ResourceIntensiveTask // you can branch your application code here. Otherwise, you don't need to. if (task is PeriodicTask) { // Execute periodic task actions here. toastMessage = "Periodic task are running."; } else { // Execute resource-intensive task actions here. toastMessage = "Resource-intensive task are running."; } // Launch a toast to show that the agent is running. // The toast will not be shown if the foreground application is running. ShellToast toast = new ShellToast(); toast.Title = "Background Agent Sample"; toast.Content = toastMessage; toast.Show(); // If debugging is enabled, launch the agent again in one minute. #if DEBUG_AGENT ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30)); #endif // Call NotifyComplete to let the system know the agent is done working. NotifyComplete(); }
b.) MainPage.xaml markup
<span style="color: blue"><</span><span style="color: #a31515">phone</span><span style="color: blue">:</span><span style="color: #a31515">PhoneApplicationPage </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Class</span><span style="color: blue">="PhoneApp1.MainPage" </span><span style="color: red">xmlns</span><span style="color: blue">="http://schemas.microsoft.com/winfx/2006/xaml/presentation" </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">x</span><span style="color: blue">="http://schemas.microsoft.com/winfx/2006/xaml" </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">phone</span><span style="color: blue">="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">shell</span><span style="color: blue">="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">d</span><span style="color: blue">="http://schemas.microsoft.com/expression/blend/2008" </span><span style="color: red">xmlns</span><span style="color: blue">:</span><span style="color: red">mc</span><span style="color: blue">="http://schemas.openxmlformats.org/markup-compatibility/2006" </span><span style="color: red">mc</span><span style="color: blue">:</span><span style="color: red">Ignorable</span><span style="color: blue">="d" </span><span style="color: red">d</span><span style="color: blue">:</span><span style="color: red">DesignWidth</span><span style="color: blue">="480" </span><span style="color: red">d</span><span style="color: blue">:</span><span style="color: red">DesignHeight</span><span style="color: blue">="768" </span><span style="color: red">FontFamily</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneFontFamilyNormal</span><span style="color: blue">}" </span><span style="color: red">FontSize</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneFontSizeNormal</span><span style="color: blue">}" </span><span style="color: red">Foreground</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneForegroundBrush</span><span style="color: blue">}" </span><span style="color: red">SupportedOrientations</span><span style="color: blue">="Portrait" </span><span style="color: red">Orientation</span><span style="color: blue">="Portrait" </span><span style="color: red">shell</span><span style="color: blue">:</span><span style="color: red">SystemTray.IsVisible</span><span style="color: blue">="True"> </span><span style="color: green"><!--LayoutRoot is the root grid where all page content is placed--> </span><span style="color: blue"><</span><span style="color: #a31515">Grid </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">="LayoutRoot" </span><span style="color: red">Background</span><span style="color: blue">="Transparent"> <</span><span style="color: #a31515">Grid.RowDefinitions</span><span style="color: blue">> <</span><span style="color: #a31515">RowDefinition </span><span style="color: red">Height</span><span style="color: blue">="Auto"/> <</span><span style="color: #a31515">RowDefinition </span><span style="color: red">Height</span><span style="color: blue">="*"/> </</span><span style="color: #a31515">Grid.RowDefinitions</span><span style="color: blue">> </span><span style="color: green"><!--TitlePanel contains the name of the application and page title--> </span><span style="color: blue"><</span><span style="color: #a31515">StackPanel </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">="TitlePanel" </span><span style="color: red">Grid.Row</span><span style="color: blue">="0" </span><span style="color: red">Margin</span><span style="color: blue">="12,17,0,28"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">="ApplicationTitle" </span><span style="color: red">Text</span><span style="color: blue">="Craziness App" </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextNormalStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">="PageTitle" </span><span style="color: red">Text</span><span style="color: blue">="Tasks Sample" </span><span style="color: red">Margin</span><span style="color: blue">="9,-7,0,0" </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextTitle1Style</span><span style="color: blue">}"/> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> </span><span style="color: green"><!--ContentPanel - place additional content here--> </span><span style="color: blue"><</span><span style="color: #a31515">Grid </span><span style="color: red">x</span><span style="color: blue">:</span><span style="color: red">Name</span><span style="color: blue">="ContentPanel" </span><span style="color: red">Grid.Row</span><span style="color: blue">="1" </span><span style="color: red">Margin</span><span style="color: blue">="12,0,12,0"> <</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Vertical" </span><span style="color: red">Name</span><span style="color: blue">="PeriodicStackPanel" </span><span style="color: red">Margin</span><span style="color: blue">="0,0,0,40"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="Periodic Agent" </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextTitle2Style</span><span style="color: blue">}"/> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Horizontal"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="name: " </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">Name</span><span style="color: blue">}" /> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Horizontal"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="is enabled" </span><span style="color: red">VerticalAlignment</span><span style="color: blue">="Center" </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">CheckBox </span><span style="color: red">Name</span><span style="color: blue">="PeriodicCheckBox" </span><span style="color: red">IsChecked</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">IsEnabled</span><span style="color: blue">}" </span><span style="color: red">Checked</span><span style="color: blue">="PeriodicCheckBox_Checked" </span><span style="color: red">Unchecked</span><span style="color: blue">="PeriodicCheckBox_Unchecked"/> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Horizontal"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="is scheduled: " </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">IsScheduled</span><span style="color: blue">}" /> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Horizontal"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="last scheduled time: " </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">LastScheduledTime</span><span style="color: blue">}" /> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Horizontal"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="expiration time: " </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">ExpirationTime</span><span style="color: blue">}" /> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Horizontal"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="last exit reason: " </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">LastExitReason</span><span style="color: blue">}" /> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Vertical" </span><span style="color: red">Name</span><span style="color: blue">="ResourceIntensiveStackPanel" </span><span style="color: red">Margin</span><span style="color: blue">="0,0,0,40"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="Resource-intensive Agent" </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextTitle2Style</span><span style="color: blue">}"/> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Horizontal"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="name: " </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">Name</span><span style="color: blue">}" /> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Horizontal"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="is enabled" </span><span style="color: red">VerticalAlignment</span><span style="color: blue">="Center" </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">CheckBox </span><span style="color: red">Name</span><span style="color: blue">="ResourceIntensiveCheckBox" </span><span style="color: red">IsChecked</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">IsEnabled</span><span style="color: blue">}" </span><span style="color: red">Checked</span><span style="color: blue">="ResourceIntensiveCheckBox_Checked" </span><span style="color: red">Unchecked</span><span style="color: blue">="ResourceIntensiveCheckBox_Unchecked"/> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Horizontal"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="is scheduled: " </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">IsScheduled</span><span style="color: blue">}" /> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Horizontal"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="last scheduled time: " </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">LastScheduledTime</span><span style="color: blue">}" /> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Horizontal"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="expiration time: " </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">ExpirationTime</span><span style="color: blue">}" /> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> <</span><span style="color: #a31515">StackPanel </span><span style="color: red">Orientation</span><span style="color: blue">="Horizontal"> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="last exit reason: " </span><span style="color: red">Style</span><span style="color: blue">="{</span><span style="color: #a31515">StaticResource </span><span style="color: red">PhoneTextAccentStyle</span><span style="color: blue">}"/> <</span><span style="color: #a31515">TextBlock </span><span style="color: red">Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding </span><span style="color: red">LastExitReason</span><span style="color: blue">}" /> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> </</span><span style="color: #a31515">StackPanel</span><span style="color: blue">> </</span><span style="color: #a31515">Grid</span><span style="color: blue">> </</span><span style="color: #a31515">Grid</span><span style="color: blue">> </span><span style="color: green"><!--Sample code showing usage of ApplicationBar--> <!--<phone:PhoneApplicationPage.ApplicationBar> <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True"> <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/> <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/> <shell:ApplicationBar.MenuItems> <shell:ApplicationBarMenuItem Text="MenuItem 1"/> <shell:ApplicationBarMenuItem Text="MenuItem 2"/> </shell:ApplicationBar.MenuItems> </shell:ApplicationBar> </phone:PhoneApplicationPage.ApplicationBar>--> </span><span style="color: blue"></</span><span style="color: #a31515">phone</span><span style="color: blue">:</span><span style="color: #a31515">PhoneApplicationPage</span><span style="color: blue">> </span>
and this is how my application screen would look like
c. MainPage.xaml.cs implementation
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using Microsoft.Phone.Scheduler; using Microsoft.Phone.Tasks; namespace PhoneApp1 { public partial class MainPage : PhoneApplicationPage { PeriodicTask periodicTask; ResourceIntensiveTask resourceIntensiveTask; string periodicTaskName = "PeriodicAgent"; string resourceIntensiveTaskName = "ResourceIntensiveAgent"; public bool agentsAreEnabled = true; bool ignoreCheckBoxEvents = false; // Constructor public MainPage() { InitializeComponent(); this.Loaded += new RoutedEventHandler(MainPage_Loaded); } void MainPage_Loaded(object sender, RoutedEventArgs e) { } private void StartPeriodicAgent() { // Variable for tracking enabled status of background agents for this app. agentsAreEnabled = true; // Obtain a reference to the period task, if one exists periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask; // If the task already exists and background agents are enabled for the // application, you must remove the task and then add it again to update // the schedule if (periodicTask != null) { RemoveAgent(periodicTaskName); } periodicTask = new PeriodicTask(periodicTaskName); // The description is required for periodic agents. This is the string that the user // will see in the background services Settings page on the device. periodicTask.Description = "This demonstrates a periodic task."; // Place the call to Add in a try block in case the user has disabled agents. try { ScheduledActionService.Add(periodicTask); PeriodicStackPanel.DataContext = periodicTask; // If debugging is enabled, use LaunchForTest to launch the agent in 30 seconds. // #if(DEBUG_AGENT) ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(30)); //#endif } catch (InvalidOperationException exception) { if (exception.Message.Contains("BNS Error: The action is disabled")) { MessageBox.Show("Background agents for this application have been disabled by the user."); agentsAreEnabled = false; PeriodicCheckBox.IsChecked = false; } if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added.")) { // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached. } PeriodicCheckBox.IsChecked = false; } catch (SchedulerServiceException) { // No user action required. PeriodicCheckBox.IsChecked = false; } } private void StartResourceIntensiveAgent() { // Variable for tracking enabled status of background agents for this app. agentsAreEnabled = true; resourceIntensiveTask = ScheduledActionService.Find(resourceIntensiveTaskName) as ResourceIntensiveTask; // If the task already exists and background agents are enabled for the // application, you must remove the task and then add it again to update // the schedule. if (resourceIntensiveTask != null) { RemoveAgent(resourceIntensiveTaskName); } resourceIntensiveTask = new ResourceIntensiveTask(resourceIntensiveTaskName); // The description is required for periodic agents. This is the string that the user // will see in the background services Settings page on the device. resourceIntensiveTask.Description = "This demonstrates a resource-intensive task."; // Place the call to Add in a try block in case the user has disabled agents. try { ScheduledActionService.Add(resourceIntensiveTask); ResourceIntensiveStackPanel.DataContext = resourceIntensiveTask; // If debugging is enabled, use LaunchForTest to launch the agent in one minute. //#if(DEBUG_AGENT) ScheduledActionService.LaunchForTest(resourceIntensiveTaskName, TimeSpan.FromSeconds(60)); //#endif } catch (InvalidOperationException exception) { if (exception.Message.Contains("BNS Error: The action is disabled")) { MessageBox.Show("Background agents for this application have been disabled by the user."); agentsAreEnabled = false; } ResourceIntensiveCheckBox.IsChecked = false; } catch (SchedulerServiceException) { // No user action required. ResourceIntensiveCheckBox.IsChecked = false; } } private void PeriodicCheckBox_Checked(object sender, RoutedEventArgs e) { if (ignoreCheckBoxEvents) return; StartPeriodicAgent(); } private void PeriodicCheckBox_Unchecked(object sender, RoutedEventArgs e) { if (ignoreCheckBoxEvents) return; RemoveAgent(periodicTaskName); } private void ResourceIntensiveCheckBox_Checked(object sender, RoutedEventArgs e) { if (ignoreCheckBoxEvents) return; StartResourceIntensiveAgent(); } private void ResourceIntensiveCheckBox_Unchecked(object sender, RoutedEventArgs e) { if (ignoreCheckBoxEvents) return; RemoveAgent(resourceIntensiveTaskName); } protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { ignoreCheckBoxEvents = true; periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask; if (periodicTask != null) { PeriodicStackPanel.DataContext = periodicTask; } resourceIntensiveTask = ScheduledActionService.Find(resourceIntensiveTaskName) as ResourceIntensiveTask; if (resourceIntensiveTask != null) { ResourceIntensiveStackPanel.DataContext = resourceIntensiveTask; } ignoreCheckBoxEvents = false; } private void RemoveAgent(string name) { try { ScheduledActionService.Remove(name); } catch (Exception) { } } } }
d.) and Hit “F5”
and below are some screen shots for reference.
- App is running and Periodic Agent is enabled to run on every 30 seconds.
now after 30 seconds scheduled tasks run and called the Scheduled Task implementation
and can see that last run status is updated and last run reason is completed.
Apologies for the Poor formatting.
Hope the code is self explanatory and since the Post is so big after the code blocks and screen shots, I am not including much explanations of this sample. You can read MSDN Reference on How to: Implement Background Agents for Windows Phone, which includes clear cut explanation of the above sample.
References:
Background Agents Overview for Windows Phone
How to: Implement Background Agents for Windows Phone
Discover more from Cloud Distilled ~ Nithin Mohan
Subscribe to get the latest posts sent to your email.