×
Namespaces

Variants
Actions
(Difference between revisions)

How to create simple Background Agent in Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search
vdharankar (Talk | contribs)
m (Vdharankar - - Summary)
influencer (Talk | contribs)
m (Influencer -)
(9 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[Category:Windows Phone]][[Category:Windows Phone 8]][[Category:Windows Phone 7.5]]
+
[[Category:Windows Phone]][[Category:Windows Phone 8]][[Category:Windows Phone 7.5]][[Category:General Programming]]
 
+
{{Abstract|This article provides a minimal example on how to create [http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202942(v=vs.105).aspx Background Agents] (Tasks) in Windows Phone.  There is a more comprehensive example on Dev Center [http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202941(v=vs.105).aspx How to implement background agents for Windows Phone].}}
{{Abstract|This article explains how to create Background Agents (Tasks) in Windows Phone }}
+
{{SeeAlso|
 
+
* [http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202942(v=vs.105).aspx Background agents for Windows Phone] (Dev Center)
 +
* [http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202941(v=vs.105).aspx How to implement background agents for Windows Phone] (Dev Center)}}
 
{{ArticleMetaData <!-- v1.2 -->
 
{{ArticleMetaData <!-- v1.2 -->
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
+
|sourcecode= [[Media:ScheduledDemoTaskAgent.zip]]  
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
|devices= <!-- Devices tested against - e.g. ''devices=Nokia 6131 NFC, Nokia C7-00'') -->
+
|devices=   ''Nokia lumia 920, lumia 900''
|sdk= <!-- SDK(s) built and tested against (e.g. [http://linktosdkdownload/ Qt SDK 1.1.4]) -->
+
|sdk= WP SDK 8.0
 
|platform= <!-- Compatible platforms - e.g. Symbian^1 and later, Qt 4.6 and later -->
 
|platform= <!-- Compatible platforms - e.g. Symbian^1 and later, Qt 4.6 and later -->
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->  
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|signing=<!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
+
|signing= <!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 
|keywords= <!-- APIs, classes and methods (e.g. QSystemScreenSaver, QList, CBase -->
 
|keywords= <!-- APIs, classes and methods (e.g. QSystemScreenSaver, QList, CBase -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|translated-by= <!-- [[User:XXXX]] -->
 
|translated-by= <!-- [[User:XXXX]] -->
|translated-from-title= <!-- Title only -->  
+
|translated-from-title= <!-- Title only -->
 
|translated-from-id= <!-- Id of translated revision -->
 
|translated-from-id= <!-- Id of translated revision -->
|review-by=<!-- After re-review: [[User:username]] -->
+
|review-by= <!-- After re-review: [[User:username]] -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 
|update-timestamp= <!-- After significant update: YYYYMMDD -->
|creationdate= <!-- Format YYYYMMDD -->
+
|creationdate= 20130121
|author= <!-- Display as link [[User:username]] -->
+
|author= [[User:Vdharankar]]
 
}}
 
}}
  
 
== Introduction ==
 
== Introduction ==
  
This article explains how to create a simple background agent in Windows Phone. There is a MSDN example on how to create a background agent but its not simple it has additional stuff in it, so if you are looking for just plain simple how to ? here it is.  
+
Windows Phone apps are made dormant when running in the background or when the phone is locked (to conserve device memory and battery life). If your application needs to perform processing when it is (may be) in the background you can use a [http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202942(v=vs.105).aspx background agent] to run activities according to some schedule.
 +
 
 +
Background agents are divided into ''Periodic Tasks'' and ''Resource-intensive Tasks''. ''Periodic Task'' can run for no more than 25 seconds every 30 minutes. This sort of agent is suitable for many common use-cases:
 +
* Downloading data from remote server and then scheduling notifications (for example, when monitoring twitter or facebook updates)
 +
* Changing lock screen wallpaper ( like the Bing app)
 +
* Synchronizing data in the background, for example emails
 +
 
 +
 
 +
Apps which require more device resources and/or which do not require a fixed update schedule, can use a resource intensive task. These tasks run when the device is connected to external power and/or connected to a WiFi network - they are very useful when you need to transfer a lot of data or perform some other long running task in the background.
 +
 
 +
This article provides a very simple example of how to create a ''Periodic Task''.
 +
 
 +
{{Tip|If you want to also understand Resource-intensive tasks then check out [http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202941(v&#61;vs.105).aspx How to implement background agents for Windows Phone] (Dev Center). This is more complicated to read, but is more comprehensive and covers both periodic and resource-intensive tasks.}}
 +
 
 +
=== Limitations===
 +
 
 +
Background agents have certain limitations, as listed below.
 +
* Background tasks can minimally be run every 30 minutes. There is a debug-only API to run them more regularly, but this is not available for released apps.
 +
* There are certain APIs which are not supported , you can check [http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202942(v=vs.105).aspx#BKMK_TypesofScheduledTasks here].
 +
* Some low power devices do not support background agents
 +
* Background tasks are limited by number on each device and can be enabled or disabled from application settings.
 +
* They do not work when power saver mode is activated.
  
 
== Basic requirements ==  
 
== Basic requirements ==  
You need to create an app project , it can be anything from simple basic windows phone app to panorama or pivote based application. Then create your background agent project in the same solution and add its reference to the main app, with necessary code ( which is hardly few lines) you can have your background agent running. You can test agents in simulator as well.
+
* You need to create an app project, it can be anything from simple basic windows phone app to panorama or pivot based application.  
 +
*Then create your background agent project in the same solution and add its reference to the main app, with necessary code (which is hardly few lines) you can have your background agent running. You can test agents in the simulator as well.
  
 
== How to.... ==
 
== How to.... ==
Line 37: Line 60:
  
  
[[File:Screenshot_(4).png]]
+
[[File:Screenshot (4).png]]
  
* Create a ''scheduled task agent'' project in Visual Studio, this should be added to the same solution , an easy way to do is, goto solution explorer of main application right click on solution and select add, select add project and automatically the project created will get added to the existing solution. Assign some suitable name to the project.
+
* Create a ''scheduled task agent'' project in Visual Studio, this should be added to the same solution. An easy way to do this is: goto solution explorer of main application, right click on solution and select add, select add project and automatically the project created will get added to the existing solution. Assign some suitable name to the project.
  
  
[[File:Screenshot_(5).png]]
+
[[File:Screenshot (5).png]]
  
  
* Next step is to add a reference to the main application it can be done by going to Solution Explorer, right click references under main project and select Add Reference option.  
+
* The next step is to add a reference to the main application. This can be done by going to Solution Explorer, right clicking references under main project and selecting the Add Reference option.  
  
  
[[File:Screenshot_(6).png]]
+
[[File:Screenshot (6).png]]
  
  
 
* Next select Solutions section on the Add Reference dialog and you should be able to see the name of your scheduled task agent project name there select it and its done.
 
* Next select Solutions section on the Add Reference dialog and you should be able to see the name of your scheduled task agent project name there select it and its done.
  
[[File:Screenshot_(7).png]]
+
[[File:Screenshot (7).png]]
  
  
* Next open ''ScheduledAgent.cs'' file from your background agent project and add following lines of code in ''OnInvoke'' method
+
* Next open '''ScheduledAgent.cs''' file from your background agent project and add following lines of code in {{Icode|OnInvoke()}} method
  
 
<code csharp>
 
<code csharp>
Line 76: Line 99:
 
</code>
 
</code>
  
Once the above code is added the Scheduled Agent or your background task is ready to fire a Toast notification whenever its called. As you may tun this app to test , dont forget to add following '''macro in at the top''' in your ''ScheduledAgent.cs'' file
+
Once the above code is added the Scheduled Agent or your background task is ready to fire a Toast notification whenever its called. As you may tun this app to test, dont forget to add following ''macro in at the top'' in your '''ScheduledAgent.cs''' file
  
 
<code csharp>
 
<code csharp>
Line 93: Line 116:
  
  
* Now next step is to setup this Agent (task) to run in background from your main app , it can be done with the help of following lines of code. Make sure you place them in your MainPage.xaml.cs file of main project, I am attaching the complete file for your exposure to the code.
+
* Now next step is to setup this Agent (task) to run in background from your main app, it can be done with the help of following lines of code. Make sure you place them in your '''MainPage.xaml.cs''' file of main project, I am attaching the complete file for your exposure to the code.
  
 
<code csharp>
 
<code csharp>
Line 180: Line 203:
 
}
 
}
 
</code>
 
</code>
We call ''LaunchForTest'' function only for debugging , which should be remove once your application goes into production environment.
+
We call {{Icode|LaunchForTest()}} function only for debugging, which should be remove once your application goes into production environment.
Make sure to remove the DEBUG macro once you are done debugging of the project which will stop calling the agent after every few seconds , which should be done only if you wish to debug the application.
+
 
 +
Make sure to remove the DEBUG macro once you are done debugging of the project which will stop calling the agent after every few seconds, which should be done only if you wish to debug the application.
 
If you keep that line as it is it may cause failure in app submission process.
 
If you keep that line as it is it may cause failure in app submission process.
  
  
 
== Summary ==
 
== Summary ==
This is how you can create the SchedulesAgent Task to run in background from using your own app. There is more information on this on MSDN, I have simplified the MSDN example as I felt the original example was overkiling and was hard to understand for a beginner due to additional stuff.
+
This is how you can create the {{Icode|SchedulesAgent}} Task to run in background from using your own app. The example is simpler than that provided by Dev Center and therefore makes it easier to understand the basic usage.
  
 
Add your feedback to comment section.
 
Add your feedback to comment section.

Revision as of 17:22, 9 February 2013

This article provides a minimal example on how to create Background Agents (Tasks) in Windows Phone. There is a more comprehensive example on Dev Center How to implement background agents for Windows Phone.

WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
SignpostIcon Code 52.png
Article Metadata
Code ExampleTested with
SDK: WP SDK 8.0
Devices(s): Nokia lumia 920, lumia 900
CompatibilityArticle
Created: vdharankar (21 Jan 2013)
Last edited: influencer (09 Feb 2013)

Contents

Introduction

Windows Phone apps are made dormant when running in the background or when the phone is locked (to conserve device memory and battery life). If your application needs to perform processing when it is (may be) in the background you can use a background agent to run activities according to some schedule.

Background agents are divided into Periodic Tasks and Resource-intensive Tasks. Periodic Task can run for no more than 25 seconds every 30 minutes. This sort of agent is suitable for many common use-cases:

  • Downloading data from remote server and then scheduling notifications (for example, when monitoring twitter or facebook updates)
  • Changing lock screen wallpaper ( like the Bing app)
  • Synchronizing data in the background, for example emails


Apps which require more device resources and/or which do not require a fixed update schedule, can use a resource intensive task. These tasks run when the device is connected to external power and/or connected to a WiFi network - they are very useful when you need to transfer a lot of data or perform some other long running task in the background.

This article provides a very simple example of how to create a Periodic Task.

Tip.pngTip: If you want to also understand Resource-intensive tasks then check out How to implement background agents for Windows Phone (Dev Center). This is more complicated to read, but is more comprehensive and covers both periodic and resource-intensive tasks.

Limitations

Background agents have certain limitations, as listed below.

  • Background tasks can minimally be run every 30 minutes. There is a debug-only API to run them more regularly, but this is not available for released apps.
  • There are certain APIs which are not supported , you can check here.
  • Some low power devices do not support background agents
  • Background tasks are limited by number on each device and can be enabled or disabled from application settings.
  • They do not work when power saver mode is activated.

Basic requirements

  • You need to create an app project, it can be anything from simple basic windows phone app to panorama or pivot based application.
  • Then create your background agent project in the same solution and add its reference to the main app, with necessary code (which is hardly few lines) you can have your background agent running. You can test agents in the simulator as well.

How to....

  • Create a simple windows phone application project as follows and give some suitable name to it.


Screenshot (4).png

  • Create a scheduled task agent project in Visual Studio, this should be added to the same solution. An easy way to do this is: goto solution explorer of main application, right click on solution and select add, select add project and automatically the project created will get added to the existing solution. Assign some suitable name to the project.


Screenshot (5).png


  • The next step is to add a reference to the main application. This can be done by going to Solution Explorer, right clicking references under main project and selecting the Add Reference option.


Screenshot (6).png


  • Next select Solutions section on the Add Reference dialog and you should be able to see the name of your scheduled task agent project name there select it and its done.

Screenshot (7).png


  • Next open ScheduledAgent.cs file from your background agent project and add following lines of code in OnInvoke() method
  protected override void OnInvoke(ScheduledTask task)
{
 
string toastMessage = "Periodic task running.";
 
ShellToast toast = new ShellToast();
toast.Title = "Background Agent Sample";
toast.Content = toastMessage;
toast.Show();
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name,TimeSpan.FromSeconds(60));
#endif
 
NotifyComplete();
}

Once the above code is added the Scheduled Agent or your background task is ready to fire a Toast notification whenever its called. As you may tun this app to test, dont forget to add following macro in at the top in your ScheduledAgent.cs file

#define DEBUG_AGENT

and after the above macro make sure you have all following namespace imports in place

using System.Diagnostics;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using System;


  • Now next step is to setup this Agent (task) to run in background from your main app, it can be done with the help of following lines of code. Make sure you place them in your MainPage.xaml.cs file of main project, I am attaching the complete file for your exposure to the code.
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using DynaLock.Resources;
using Microsoft.Phone.Scheduler;
 
namespace Application1
{
public partial class MainPage : PhoneApplicationPage
{
PeriodicTask periodicTask;
 
 
string periodicTaskName = "PeriodicAgent";
// Constructor
 
public MainPage()
{
InitializeComponent();
 
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
agentsAreEnabled = true;
 
// Obtain a reference to the period task, if one exists
periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
 
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);
 
// If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(10));
#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;
 
}
 
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.
 
}
 
}
catch (SchedulerServiceException)
{
// No user action required.
}
 
 
}
private void RemoveAgent(string name)
{
try
{
ScheduledActionService.Remove(name);
}
catch (Exception)
{
}
}
}
}

We call LaunchForTest() function only for debugging, which should be remove once your application goes into production environment.

Make sure to remove the DEBUG macro once you are done debugging of the project which will stop calling the agent after every few seconds, which should be done only if you wish to debug the application. If you keep that line as it is it may cause failure in app submission process.


Summary

This is how you can create the SchedulesAgent Task to run in background from using your own app. The example is simpler than that provided by Dev Center and therefore makes it easier to understand the basic usage.

Add your feedback to comment section.

968 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×