You are on page 1of 28

M6: Background Agents

New updates
from
Background
Agent
Andy Wigley | Microsoft Technical Evangelist
Rob Tiffany | Microsoft Enterprise Mobility Strategist
Target Agenda | Day 1
Module and Topic | 10-minute breaks after each session / 60-minute meal break
Planned
Duration
1a - Introducing Windows Phone 8 Application Development | Part 1 50:00
1b - Introducing Windows Phone 8 Application Development | Part 2 50:00
2 - Designing Windows Phone Apps 50:00
3 - Building Windows Phone Apps 50:00
4 - Files and Storage on Windows Phone 8 50:00
Meal Break | 60-minutes 60:00
5 - Windows Phone 8 Application Lifecycle 50:00
6 - Background Agents 25:00
7 - Tiles and Lock Screen Notifications 25:00
8 - Push Notifications 30:00
9 - Using Phone Resources on Windows Phone 8 50:00
Target Agenda | Day 2
Module and Topic | 10-minute breaks after each session / 60-minute meal break
Planned
Duration
10 - App to App Communication 35:00
11 - Network Communication on Windows Phone 8 50:00
12 - Proximity Sensors and Bluetooth 35:00
13 - Speech Input on Windows Phone 8 35:00
14 - Maps and Location on Windows Phone 8 35:00
15 - Wallet Support 25:00
16 - In App Purchasing 25:00
Meal Break | 60-minutes 60:00
17 - The Windows Phone Store 50:00
18 - Enterprise Applications in Windows Phone 8: Architecture and Publishing 50:00
19 - Windows 8 and Windows Phone 8 Cross Platform Development 50:00
20 Mobile Web 50:00
Module Agenda
Windows Phone task management
Multi-tasking with background agents
Creating tasks in Visual Studio
File transfer tasks
Background notifications
Foreground Tasks
Normally a Windows Phone application runs in the foreground
Has access to screen and interacts directly with the user of the phone
At any given time one application is running in the foreground
Although others may be in the memory of the phone and can be selected
as required
This is to ensure the best possible performance and battery life for the
phone user
Background Agents
A Windows Phone application can start a background agent to work for it
It is a PeriodicTask, ResourceIntensiveTask or both at the same time
There is only one agent allowed per application
The agent can run when the main application is not in the foreground
An agent is not equivalent to a foreground application running in
the background
It is limited in what it can do and the access it has to the processor and
other phone facilities

Background Agent Health Warning
The number of agents allowed to be active at one time is restricted by the Windows Phone
operating system
If the right conditions do not arise for an agent it will not be started
Background agents only run in situations where the operating system feels able to give
them access to the processor
If the phone goes into Power Saver mode it may stop running background
agents completely
Users can also manage the agents running on their phone and may chose
to disable them

Agents and Tasks
A Task is the scheduling type you request when you schedule a background agent to run
It is managed by the operating system which runs the agent at the appointed time
There are two kinds of Tasks
Periodic tasks that are run every now and then
Resource intensive tasks that run when the phone is in a position to let them
The background Agent is the actual code functionality you write which runs in the
background and which does the work
The agent code is implemented in a class that derives from BackgroundAgent
The class is created as part of a Scheduled Task Agent Project
PeriodicTask Agents
A PeriodicTask Agent runs every now and then
Typically every 30 minutes or so, depending on loading on the phone
It is intended to perform a task that should be performed regularly
and complete quickly
The agent is allowed to run for 25 seconds or so
Memory usage allowed<= 6 MB
Unscheduled after two consecutive crashes
The phone sets a limit on the maximum number of active agents at any time
Good for location tracking, polling background services, tile updates
ResourceIntensive Agents
Resource Intensive Agents run when the phone is in a position where it can usefully
perform some data processing:
When the phone is powered by the mains
When the battery is >90% charged
When the phone is connected to WiFi
When the phone is not being used (Lock screen displayed)
A resource intensive agent can run for up to 10 minutes
Memory usage allowed<= 6 MB
Unscheduled after two consecutive crashes
Good for synchronisation with a host service, unpacking/preparing resources,
compressing databases

Dual purpose Agents
It is possible for an application to perform both periodic and resource intensive
work in the background
This can be achieved using a single background agent class, run from both
kinds of task
The agent will run periodically and when the phone is in a position to allow
resource intensive work
When the agent starts it can determine the context in which it is running and
then behave appropriately



Tiles
Toast
Location
Network
R/W ISO store
Sockets
Display UI
XNA libraries
Microphone and camera
Sensors
Play audio
(may only use background
audio APIs)
Background Agent Functionality
Location Tracker
The Location Tracker program is a simple
logging application
It tracks the location of the phone by using a background agent
to regularly store the location of the phone in a text log file
The agent will update the position even when the log program
is not active
Creating a Background Agent
A background agent is added to
the application solution as a
Scheduled Task
There is a Visual Studio template
just for this
This agent will contain the code
that runs when the agent is active
The Captains Log Solution File
The solution file contains two projects
LocationLogger: the Windows Phone project
which is the main application
LocationLogTaskAgent: the background agent to
perform the tracking
Solutions can contain many types of
different projects
When the solution is built all the assembly file
outputs will be combined and sent to the phone
Connecting the Agent Project
The CaptainsLog project contains a reference to the output
of the LocationTaskAgent project
The foreground application does not directly reference any
objects in the agent class in code
Nonetheless, we have to explicitly link these two projects
by adding a reference to the LocationTaskAgent output to
the CaptainsLog project
Background Agent Code
We must implement the agent functionality in the OnInvoke method
It notifies the run time system when it has completed
namespace LocationLogTaskAgent
{
public class ScheduledAgent : ScheduledTaskAgent
{
protected override void OnInvoke(ScheduledTask task)
{
//TODO: Add code to perform your task in background
NotifyComplete();
}
}
}

Sharing Data with Background Agents
First thing agent does is load the log string from isolated storage
It is going to append the current location on the end of this string
protected override void OnInvoke(ScheduledTask task)
{
string message ="";
string logString = "";
if (LoadLogFromIsolatedStorageFile() {
message = "Loaded";
}
else {
message = "Initialised";
}
...
}
Concurrent Data Access
Protect access to files in Isolated Storage by using a named Mutex
Make sure you release the mutex
public bool LoadLogFromIsolatedStorageFile()
{
mut.WaitOne(); // Wait until it is safe to enter

try {
// read the file here
return true;
}
catch {
LogText = "";
return false;
}
finally {
mut.ReleaseMutex(); // Release the Mutex.
}
}
The code shown in this sample gets a new location whenever the Periodic agent runs
Every 30 minutes or so
Windows Phone 8 supports continuous background location tracking
Suitable for Run Tracking apps and Turn-by-Turn navigation
This is not covered here!
See the Location and Maps module
Background Location Tracking
Showing a Notification
The background task can pop up a toast notification to deliver a message
If the user taps the message it will start up the
foreground application
Toast messages will not appear if the foreground application is active
protected override void OnInvoke(ScheduledTask task)
{
...
ShellToast toast = new ShellToast();
toast.Title = "Location Log";
toast.Content = message;
toast.Show();
...
}
Scheduling the Background Agent
PeriodicTask t;
t = ScheduledActionService.Find(taskName) as PeriodicTask;
bool found = (t != null);
if (!found)
{
t = new PeriodicTask(taskName);
}
t.Description = description;
t.ExpirationTime = DateTime.Now.AddDays(10);
if (!found)
{
ScheduledActionService.Add(t);
}
else
{
ScheduledActionService.Remove(taskName);
ScheduledActionService.Add(t);
}
Debugging a Background Task
It would be annoying if we had to wait 30 minutes to get code in the agent running so we
could debug it
When we are debugging we can force the service to launch the agent
Such code can be conditionally compiled and excluded from the release build
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(60));
#endif
Demo 1:
Location Logging
What we Have Just Seen
The Location Logging application fired off a background task
The task began running even if the Location Log application is still running
in the foreground
The background task loaded location information from the phone and added it to the log
file that could then be displayed later
The background task displayed popup notifications each time that it ran

Background Agent Tips
Renew often
You must reschedule agents from your foreground app at least every two weeks
Do not implement critical functionality in a background agent
User can disable them
OS can suspend them in low battery situation
If you need more reliable execution of code outside your application and need to update
Tiles or send Toast notifications, consider Push Notifications
Review
An application can create background processes
Periodic Task tasks run every 30 minutes or so as scheduled by the OS
ResourceIntensive tasks run when the device is connected to mains power, the battery is
charged to 90% or better and the phone is not in use
Audio Playback run alongside the application
Applications and their background processes can communicate via the local folder which is
common to both
Visual Studio can be used to debug background tasks in the same way as
foreground applications

The information herein is for informational
purposes only an represents the current view of
Microsoft Corporation as of the date of this
presentation. Because Microsoft must respond
to changing market conditions, it should not be
interpreted to be a commitment on the part of
Microsoft, and Microsoft cannot guarantee the
accuracy of any information provided after the
date of this presentation.
2012 Microsoft Corporation.
All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION
IN THIS PRESENTATION.