With the release of Windows Phone 7 Mango, you now have the ability to multitask (scheduled multitask) by using background agents. Background agents allow you to do things when your application is not running.
It is important to understand that the OS is responsible for determining when your background agent can run and is determined by a number of factors. It is also dependent on the type of Background Agent you use.
For both types of Agents you are constrained by the following :
Periodic Agents (PeriodicTask) are used when you want a “semi” predictable action to fire. But they are constrained to the following. For example, you can use Periodic Agents for collecting quick GPS coordinates or updating an RSS feed.
Resource-intensive Agents (resourceIntensiveTask) can be used for more intensive items like downloading larger files or coping database entries to a replication server. But you must keep in mind that they have some specific constraints as well.
What this means is that it MAY never run. The best case scenario is the user will have their phone connected to their WiFi when they plug it in at night.
But …. after all of that, it is pretty easy to use. All you need to do is
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 running."; } else { // Execute resource-intensive task actions here. toastMessage = "Resource-intensive task 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(60)); #endif // Call NotifyComplete to let the system know the agent is done working. NotifyComplete(); }
The one caveat is that it can sometimes be difficult to debug in an emulator. If you have a developer phone you will have a much easier time debugging it on the device. If you have any questions, let me know.