×
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)
hamishwillee (Talk | contribs)
m (Hamishwillee - Bot update - Fix metadata)
Line 10: Line 10:
 
|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]]
 
}}
 
}}
  
Line 31: Line 31:
  
 
== 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 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.
  
 
== How to.... ==
 
== How to.... ==
Line 37: Line 37:
  
  
[[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 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]]
  
  
Line 48: Line 48:
  
  
[[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]]
  
  
Line 76: Line 76:
 
</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 93:
  
  
* 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 180:
 
}
 
}
 
</code>
 
</code>
We call ''LaunchForTest'' function only for debugging , which should be remove once your application goes into production environment.
+
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.
+
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.
  

Revision as of 09:44, 23 January 2013


This article explains how to create Background Agents (Tasks) in Windows Phone

WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
SignpostIcon Code 52.png
Article Metadata
CompatibilityArticle
Created: vdharankar (21 Jan 2013)
Last edited: hamishwillee (23 Jan 2013)

Contents

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.

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.

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 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


  • 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.


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. 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.

Add your feedback to comment section.

998 page views in the last 30 days.
×