08.push notifications

63
Push Notifications Nguyen Tuan | Microsoft Certified Trainer

Upload: nguyen-tuan

Post on 05-Dec-2014

141 views

Category:

Mobile


2 download

DESCRIPTION

Push notification with Windows Phone.

TRANSCRIPT

Page 1: 08.Push Notifications

Push Notifications

Nguyen Tuan | Microsoft Certified Trainer

Page 2: 08.Push Notifications

Agenda

• Introduction to Push Notification

• Push Notifications and Live Tiles

• Three Kinds of Notifications

• Windows Phone task management

• Multi-tasking with background agents

• Creating tasks in Visual Studio

• File transfer tasks

• Background notifications

• Background music playback tasks

Page 3: 08.Push Notifications

NotificationsLots of ways to display notifications

Page 4: 08.Push Notifications

Push Notifications

8/16/2014

Page 5: 08.Push Notifications

Push Notifications and Live Tiles

• Push Notifications offer developers a way to send timely information relating to their applications even when they are not running

+

• Windows phone has the unique ability to provide the end user glanceable access to the information they care most about, via Live Tiles

Page 6: 08.Push Notifications

Push Notifications

Server-initiated communication

Enable key background scenarios

Preserve battery life and user experience

Prevent polling for updates

Page 7: 08.Push Notifications

Three Kinds of Notifications

• Raw• Notification message content is application-specific• Delivered directly to app only if it is running

• Toast• Specific XML schema• Content delivered to app if it is running• If app is not running, system displays Toast popup using notification message content

• Tile• Specific XML schema• Never delivered to app • If the Tile is currently pinned to the Start screen, system updates it using notification

message content

7http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402558(v=vs.105).aspx

Page 8: 08.Push Notifications

Demo: SendToastToastNotificationClient

8

Page 9: 08.Push Notifications

Push Notification Data Flow

URI to the service:

"http://notify.l ive.com/throttledthirdparty/01.00/AAFRQHgiiMWNTYrRDXAH

Qtz-AgrNpzcDAwAAAAQOMDAwMDAwMDAwMDAwMDA"Push enabled applications

Notifications service

HTTP POSTthe message

Push endpoint is established. URI is created for the endpoint.

1

2

3

Third-party service

MPNS:Microsoft

hosted server

Send PN Message

4

Page 10: 08.Push Notifications

Push Notification Features

• Tile updates can update any display element of each of the Tile templates• Be careful to downgrade updates sent to 7.1 clients

• 30 subscription endpoints allowed per phone

• Maximum size of a notification is 1KB for the header and 3KB for the payload.

• Unauthenticated Web Service limited to 500 push notifications per subscription per day

• Authenticated Web Services are recommended• Communication uses HTTPS channel• No limit• Able to register a callback request

Page 11: 08.Push Notifications

Push notification triggers

123

4

<?xml version=“1.0”>Type = raw, Data = Man City....

</xml>

Page 12: 08.Push Notifications

Toast Message Content

• Used by system to display Toast message if app not running

• Navigates to page specified in <Param> (if supplied)

• If app is already running

• ShellToastNotificationReceived event fires

• <Text1> and <Text2> values in event args as Dictionary<string, string>

12

Page 13: 08.Push Notifications

Toast Message Content• Use the following HTTP headers:

• Where <batching interval> is 3 – Immediate delivery, 13 – delivered within 450 seconds, 23 – delivered within 900 seconds

13

string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +

"<wp:Notification xmlns:wp=\"WPNotification\">" +

"<wp:Toast>" +

"<wp:Text1>WEATHER ALERT</wp:Text1>" +

"<wp:Text2>Stormy</wp:Text2>" +

"<wp:Param>/page1.xaml?value1=1234<wp:Param>" +

"</wp:Toast>" +

"</wp:Notification>";

sendNotificationRequest.ContentType = "text/xml";sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");sendNotificationRequest.Headers.Add("X-NotificationClass", "<batching interval>");

Page 14: 08.Push Notifications

Tile Message Content

14

•Tile messages are never delivered to the app

•There are specific schemas for the a Tile update message for each of the three Tile

Templates: Flip, Cycle and Iconic

•Only Tiles using Flip and Iconic templates can be updated with images at remote URLs

•Remote Images limited to 80KB and must download in 30 seconds or less

•V7.x clients cannot consume these new templates. Recommend you:

• In your app, capture the device unique ID, the push URI, the OS version and the app

version. Send this data to your Web service registration method

•Make sure you only send the new templates to compatible new OS versions/app versions!

•Use the following HTTP headers:sendNotificationRequest.ContentType = "text/xml";sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", “token");sendNotificationRequest.Headers.Add("X-NotificationClass", "<batching interval>");

Page 15: 08.Push Notifications

FlipTile Template Tile Message Schema

<?xml version="1.0"?><wp:Notification xmlns:wp="WPNotification" Version="2.0">

<wp:Tile Id="[TileId]" Template="FlipTile"><wp:SmallBackgroundImage Action="Clear">[sm tile img URI]</wp:SmallBackgroundImage><wp:WideBackgroundImage Action="Clear">[front of wd tile img URI]</wp:WideBackgroundImage><wp:WideBackBackgroundImage Action="Clear">[back of wd tile imgURI]</wp:WideBackBackgroundImage><wp:WideBackContent Action="Clear">[back of wd tile content text]</wp:WideBackContent><wp:BackgroundImage Action="Clear">[front of med tile img URI]</wp:BackgroundImage><wp:Count Action="Clear">[count]</wp:Count><wp:Title Action="Clear">[title text]</wp:Title><wp:BackBackgroundImage Action="Clear">[back of med tile img URI]</wp:BackBackgroundImage><wp:BackTitle Action="Clear">[back of tile title text]</wp:BackTitle><wp:BackContent Action="Clear">[back of med tile content text]</wp:BackContent>

</wp:Tile></wp:Notification>

8/16/2014 15

Page 16: 08.Push Notifications

CycleTile Template Tile Message Schema

<?xml version="1.0"?><wp:Notification xmlns:wp="WPNotification" Version="2.0">

<wp:Tile Id="[TileId]" Template="CycleTile"><wp:SmallBackgroundImage Action="Clear">[sm tile img URI]</wp:SmallBackgroundImage><wp:CycleImage1 Action="Clear">[photo 1 img URI]</wp:CycleImage1><wp:CycleImage2 Action="Clear">[photo 2 img URI]</wp:CycleImage2><wp:CycleImage3 Action="Clear">[photo 3 img URI]</wp:CycleImage3><wp:CycleImage4 Action="Clear">[photo 4 img URI]</wp:CycleImage4><wp:CycleImage5 Action="Clear">[photo 5 img URI]</wp:CycleImage5><wp:CycleImage6 Action="Clear">[photo 6 img URI]</wp:CycleImage6><wp:CycleImage7 Action="Clear">[photo 7 img URI]</wp:CycleImage7><wp:CycleImage8 Action="Clear">[photo 8 img URI]</wp:CycleImage8><wp:CycleImage9 Action="Clear">[photo 9 img URI]</wp:CycleImage9><wp:Count Action="Clear">[count]</wp:Count><wp:Title Action="Clear">[title text]</wp:Title>

</wp:Tile></wp:Notification>

8/16/2014 16

Page 17: 08.Push Notifications

IconicTile Template Tile Message Schema

<?xml version="1.0"?><wp:Notification xmlns:wp="WPNotification" Version="2.0">

<wp:Tile Id="[TileId]" Template="IconicTile"><wp:SmallIconImage Action="Clear">[sm icon img URI]</wp:SmallIconImage><wp:IconImage Action="Clear">[med/wd icon img URI]</wp:IconImage><wp:WideContent1 Action="Clear">[wd tile content line 1]</wp:WideContent1><wp:WideContent2 Action="Clear">[wd tile content line 2]</wp:WideContent2><wp:WideContent3 Action="Clear">[wd tile content line 3]</wp:WideContent3><wp:Count Action="Clear">[count]</wp:Count><wp:Title Action="Clear">[title text]</wp:Title><wp:BackgroundColor Action="Clear">[hex ARGB background color of tile]</wp:BackgroundColor>

</wp:Tile></wp:Notification>

8/16/2014 17

Page 18: 08.Push Notifications

Raw Message Content

• Use the following HTTP headers:

• Where <batching interval> is 3 – Immediate delivery, 13 – delivered within 450 seconds, 23 –delivered within 900 seconds

• Message Content is application-specific – only gets delivered to running app

• For example use XML to format data

18

string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +"<root>" +

"<Value1>SomeUserValue<Value1>" +"<Value2>SomeOtherUserValue<Value2>" +

"</root>";

sendNotificationRequest.ContentType = "text/xml";sendNotificationRequest.Headers.Add("X-NotificationClass", "<batching interval>");

Page 19: 08.Push Notifications

Demo: Push Notifications

19

Page 20: 08.Push Notifications

Response Custom Headers

• Response Code: HTTP status code (200 OK)• Notification Status

• Notification received by the Push Notification Service• For example: “X-NotificationStatus:Received”

• DeviceConnectionStatus• The connection status of the device• //For example: X-DeviceConnectionStatus:Connected

• SubscriptionStatus• The subscription status• //For example: X-SubscriptionStatus:Active

• More information • http://msdn.microsoft.com/en-us/library/ff402545(v=VS.92).aspx

Page 21: 08.Push 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

21

Page 22: 08.Push Notifications

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

22

Page 23: 08.Push Notifications

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

23

Page 24: 08.Push Notifications

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

24

Page 25: 08.Push Notifications

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

25

Page 26: 08.Push Notifications

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

26

Page 27: 08.Push Notifications

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

27

Page 28: 08.Push Notifications

Background Agent Functionality

Page 29: 08.Push Notifications

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

29

Page 30: 08.Push Notifications

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

30

Page 31: 08.Push Notifications

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

31

Page 32: 08.Push Notifications

Connecting the Agent Project

• The CaptainsLog project contains a reference to the output of the LocationTaskAgentproject

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

32

Page 33: 08.Push Notifications

Background Agent Code

• We must implement the agent functionality in the OnInvokemethod

• 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 backgroundNotifyComplete();

}}

}

Page 34: 08.Push Notifications

Sharing Data with Background Agents

protected override void OnInvoke(ScheduledTask task){

string message ="";string logString = "";if (LoadLogFromIsolatedStorageFile() {

message = "Loaded";}else {

message = "Initialised";}...

}

Page 35: 08.Push Notifications

Concurrent Data Access

35

• 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 herereturn true;

}catch {

LogText = ""; return false;

}finally {

mut.ReleaseMutex(); // Release the Mutex. }

}

Page 36: 08.Push Notifications

Selecting the Location capability• In Windows Phone 8 a new

application does not have all its capabilities enabled when it is created

• The WMAppManifest.xml file in the Properties folder must be opened and the location tracking capability selected

• Otherwise the program will fail to run

• Don’t forget to specify capabilities in your foreground app project that your background agent needs

8/16/2014 36

Page 37: 08.Push Notifications

Obtaining the Phone Location

37

protected override void OnInvoke(ScheduledTask task){

...GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();watcher.Start();string positionString = watcher.Position.Location.ToString() +

System.Environment.NewLine;...

}

Page 38: 08.Push Notifications

Storing the Phone Location

38

• The background agent now constructs a location message, with a timestamp and then saves the log string back to isolated storage

• This string can be displayed for the user by the foreground application

protected override void OnInvoke(ScheduledTask task){

...logString = logString + timeStampString + " " + positionString;

SaveLogToIsolatedStorageFile ();...

}

Page 39: 08.Push Notifications

• 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

8/16/2014 39

Page 40: 08.Push Notifications

Showing a Notification

40

• 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();...

}

Page 41: 08.Push Notifications

Scheduling the Background Agent

41

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);}

Page 42: 08.Push Notifications

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

42

#if DEBUG_AGENTScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(60));#endif

Page 43: 08.Push Notifications
Page 44: 08.Push Notifications

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

Page 45: 08.Push Notifications

Background File Transfers

Page 46: 08.Push Notifications

File Transfer Tasks

• It is also possible to create a background task to transfer files to and from your application’s isolated storage

• The transfers will take place when the application is not running

• An application can monitor the state of the downloads and display their status

• Files can be fetched from HTTP or HTTPS hosts• At the moment FTP is not supported

• The system maintains a queue of active transfers and services each one in turn

• Applications can query the state of active transfers

46

Page 47: 08.Push Notifications

Background Transfer Policies

• There are a set of policies that control transfer behaviour• Maximum Upload file size: 5Mb

• Maximum Download file size over cellular (mobile phone) data: 20Mb

• Maximum Download file size over WiFi: 100Mb

• These can be modified by setting the value of TransferPreferenceson a particular transfer

• Maximum number of Background Transfer Requests per app: 25 • Increased from 5 in Windows Phone OS 7.1

47

Page 48: 08.Push Notifications

The BackgroundTransfer namespace

• The Background Transfer services are all provided from the BackgroundTransfernamespace

• You do not need to create any additional projects to create and manage background transfers

48

using Microsoft.Phone.BackgroundTransfer;

Page 49: 08.Push Notifications

Creating a Background Transfer

49

• This creates a request and sets the source for the transfer

• It also sets the transfer method• POST can be used to send files to the server

Uri transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute);

// Create the new transfer request, passing in the URI of the file to // be transferred.transferRequest = new BackgroundTransferRequest(transferUri);

// Set the transfer method. GET and POST are supported.transferRequest.Method = "GET";

Page 50: 08.Push Notifications

Setting the Transfer Destination

50

• Files are transferred into isolated storage for an application

• This code also sets the preferences for the transfer• TransferPreferences has a number of different settings

string downloadFile = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);

// Build the URIdownloadUri = new Uri("shared/transfers/" + downloadFile,

UriKind.RelativeOrAbsolute);transferRequest.DownloadLocation = downloadUri;

// Set transfer optionstransferRequest.TransferPreferences =

TransferPreferences.AllowCellularAndBattery;

Page 51: 08.Push Notifications

try {BackgroundTransferService.Add(transferRequest);

}catch (InvalidOperationException ex) {

MessageBox.Show("Unable to add background transfer request. "+ ex.Message);

}catch (Exception) {

MessageBox.Show("Unable to add background transfer request.");}

Starting the Transfer

51

• This adds a transfer request to the list of active transfers

• An application can have a maximum of 25 transfers active at one time

• The Add method will throw exceptions if it fails

Page 52: 08.Push Notifications

Monitoring the Transfer

52

• The application can subscribe to events fired by a TransferRequest• TransferProcessChanged is used for progress bars

• TransferStatusChanged is used when the transfer completes or fails

// Bind event handlers to the progess and status changed eventstransferRequest.TransferProgressChanged +=

new EventHandler<BackgroundTransferEventArgs>(request_TransferProgressChanged);

transferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(

request_TransferStatusChanged);

Page 53: 08.Push Notifications

Transfer Progress Changed

53

• When the progress changes our application can update a progress display

• You could use a progress bar here

void request_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)

{statusTextBlock.Text = e.Request.BytesReceived + " received.";

}

Page 54: 08.Push Notifications

void request_TransferStatusChanged(object sender, BackgroundTransferEventArgs e) {

switch (e.Request.TransferStatus) {case TransferStatus.Completed:

// If the status code of a completed transfer is 200 or 206, the// transfer was successfulif (transferRequest.StatusCode == 200 ||

transferRequest.StatusCode == 206){

// File has arrived OK – use it in the program}

...

Transfer Status Changed

54

• This code checks that the file has arrived OK

Page 55: 08.Push Notifications

Removing a Transfer

55

• When a transfer has completed it is not automatically removed by the system

• This can cause completed transfers to block any new ones

• It is important that completed transfers are removed

• Note that the remove process may throw an exception if it fails

try {BackgroundTransferService.Remove(transferRequest);

}catch {}

Page 56: 08.Push Notifications
Page 57: 08.Push Notifications

Transfer Management

• An application can find out how many file transfers it has active• It will have to do this when it is restarted, as file transfers will continue even

when the application is not running

• It can then perform transfer management as required

• There is a good example of transfer list management on MSDN

http://msdn.microsoft.com/en-us/library/hh202953.aspx

Page 58: 08.Push Notifications

Getting Active Transfers

IEnumerable<BackgroundTransferRequest> transferRequests;...private void UpdateRequestsList(){

// The Requests property returns new references, so make sure that// you dispose of the old references to avoid memory leaks.if (transferRequests != null) {

foreach (var request in transferRequests) {request.Dispose();

}}transferRequests = BackgroundTransferService.Requests;

}

Page 59: 08.Push Notifications

Supplying Credentials for Transfers

string username = "user";string password = "pass@word1";

Uri transferUri = new Uri("https://www.contoso.com/getsecure/");BackgroundTransferRequest myReq = new BackgroundTransferRequest(transferUri);myReq.Method = "GET";

string usernamePassword = username + ":" + password;myReq.Headers.Add("Authorization", "Basic "

+ Convert.ToBase64String(StringToAscii(usernamePassword)));string downloadFile = "test";Uri downloadUri = new Uri("shared/transfers/test", UriKind.RelativeOrAbsolute);myReq.DownloadLocation = downloadUri;BackgroundTransferService.Add(myReq);

Page 60: 08.Push Notifications

Background Audio

Page 61: 08.Push Notifications

Audio Playback Agents

• Also possible to create an Audio Playback Agent that will manage an application controlled playlist

• The mechanism is the same as for other background tasks

• The audio can be streamed or held in the application isolated storage

61

Page 62: 08.Push Notifications
Page 63: 08.Push Notifications

Summary• Push Notifications are an efficient and battery-friendly way of sending

notifications from a server to an app on a phone

• Raw notifications go only to a running app

• Toast notifications go to the app if it is running, otherwise display as a popup on the phone

• Tile notifications are used only to update tiles on the Start Screen