Using Background Agents in your Windows Phone 7.5 (Mango) Apps

Overview

Windows Phone 7.5, codenamed Mango, added around 500 new features over the first version of Windows Phone platform. One of the features is the ability to schedule tasks and execute them through background agents. They can execute even when the application is not running in the foreground.

There are two types of scheduled tasks one can use in a Windows Phone application.

  1. Periodic agents are tasks that run at regular intervals for a small amount of time. An example would be periodic data synchronization done by some social application like Facebook. This is implemented by PeriodicTask class.
  2. Resource-intensive agents are tasks that run for a longer period of time, (like weekly application updates being downloaded in the background). This is implemented by ResourceIntensiveTask class.

Before using Background agents in their application, one needs to understand that certain APIs are not allowed to be called from a background agent. APIs for Camera, VibrateController, Radio, BackgroundAudioPlayer, Sensors, etc. are not allowed to be back from a background agent, and hence cannot be executed by a scheduled task.

The most used APIs in a scheduled task are of type ShellToast and HttpWebRequest.

Hands-On

Create a Windows Phone project in Visual Studio. Add a new project to this solution of the type "Windows Phone Scheduled Task Agent" called WindowsPhoneScheduledTaskAgent.

Open up the ScheduledAgent.cs file that is auto-generated by the Visual Studio Editor.

In the OnInvoke Method, add the following code.

protected override void OnInvoke(ScheduledTask task)
        {
            //TODO: Add code to perform your task in background
            ShellToast backgroundToast = new ShellToast();
            backgroundToast.Title = "Scheduled Task";
            backgroundToast.Content = "Running...";
            backgroundToast.Show();
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
 
 
            NotifyComplete();
        }

Now, in our main project file, add a button control (called buttonAddPeriodicTask) to the MainPage.xaml. Add a PeriodicTask variable to the class.

PeriodicTask myPeriodicTask;

Now In the buttonAddPeriodicTask's click event, add the following code

private void buttonAddPeriodicTask_Click(object sender, RoutedEventArgs e)
        {
            myPeriodicTask = ScheduledActionService.Find("My periodic task") as PeriodicTask;
            if (myPeriodicTask != null)
            {
                ScheduledActionService.Remove("My periodic task");
            }
            myPeriodicTask = new PeriodicTask("My periodic task");
            myPeriodicTask.Description = "This demonstrates a periodic task.";

            ScheduledActionService.Add(myPeriodicTask);
            stackPanel1.DataContext = myPeriodicTask;
            ScheduledActionService.LaunchForTest("My periodic task", TimeSpan.FromSeconds(10));
 
        }

Compile and execute the project. If you are having issues compiling, you can download a working sample of code from here.

Click the
Figure 1: Click the "Add periodic task" button

Click the "Add periodic task" button and then in a couple of seconds, click the "Windows" button to go to the home screen.

You will notice that after around 20 seconds, you will notice a notification at the topic of the screen as displayed below.

Notification from the scheduled task
Figure 2: Notification from the scheduled task

This is the notification from the scheduled task that appeared, indicating that the scheduled task has run.

If you are using PeriodicTask, as in our demo, you should see the notification appear every 20 seconds until the phone is rebooted or the emulator is shutdown.

Summary

In this article, we learned how to use background agents to run scheduled tasks in Windows Phone 7.5 applications. I hope you have found this information useful.



About the Author

Vipul Vipul Patel

Vipul Patel is a Software Engineer currently working at Microsoft Corporation, working in the Office Communications Group and has worked in the .NET team earlier in the Base Class libraries and the Debugging and Profiling team. He can be reached at vipul_d_patel@hotmail.com

Related Articles

Downloads

Comments

  • the notification appear every 20 seconds

    Posted by likewer on 04/01/2013 06:17pm

    i testing ady, but the notification will not appear in every 20 seconds. what wrong?

    Reply
  • dependency and reference

    Posted by mauro on 05/30/2012 01:03am

    please, specify that you need to add dependency from main project to agent and add reference to main project to agent

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Organizations are increasingly gravitating toward mobile-first application development as they assess the need to revamp their application portfolios to support touch computing and mobility. Consumerization has brought higher expectations for application usability along with the mobile devices themselves. Enterprises are increasingly shifting their new application acquisitions and development efforts toward mobile platforms. With this backdrop, it is natural to expect application platform vendors to invest in …

  • Gain buy-in, choose the right tools, and encourage employees to participate. Whether you need help introducing social media or making your efforts more successful, this is the guide for you. It contains 140 tips in tweet form (140 characters or less) with ideas for promoting social media, deciding which venues to use, and encouraging participation. Plus, the guide contains links to social media statistics, informative websites, and other resources.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date