August 4, 2011

Multitasking in Windows Phone 7 [Mango] - Part II

In my previous post, I talked about different ways [or options] to build applications which can do multitasking on Windows Phone [Mango] devices. In this post, we’ll do hands-on on one of the option – PeriodicTask

From MSDN: PeriodicTask inherits from the base classes ScheduledTask and ScheduledAction. It allows applications to perform processing even when the main application is not in the foreground. This class is used for tasks that need to run regularly for a small amount of time and are allowed a very limited amount of device resources.

To create application which will run in background, you’ll need to “host” it via another application of type “Background Agent”. And this involves three steps:

Step 01: Create a normal Windows Phone 7.1 [Mango] Application

In this step, you create a normal WP application, which you want to run in the background. However, keep in mind that few APIs will be unavailable while running your app in the background. More information here Unsupported APIs for Scheduled Tasks for Windows Phone 

Step 02: Create Windows Phone Scheduled Task Agent

Create a new project of type Windows Phone Scheduled Task Agent. It will give you OnInvoke method, which will run the scheduled task and do additional job, which you want to run in the background.

Step 03: Modifications in main application:

In your main application [which you created in Step 01] add reference to this Windows Phone Scheduled Task Agent application, and notice the WMAppManifest file in Properties tab. It’ll have following information embedded:

image

Now, add a button [button1] to main page and add following code your main application:

image

Here, you’re creating an object of PeriodicTask and passing agent application as parameter from main application.

That’s it. Now run your application, click on a button to start the background service. On Phone, go to settings > Applications > Background Tasks and there you should be able to see your application running in background:

image

Now, you can run your application again and see how it’s behaving.

Namaste

Happy Coding

Mayur Tendulkar | www.mayurtendulkar.com