Upload
windowsphonerocks
View
395
Download
1
Embed Size (px)
DESCRIPTION
Building Apps for Windows Phone 8.1 Jump Start . Videos at: http://channel9.msdn.com/Series/Building-Apps-for-Windows-Phone-8-1
Citation preview
Andy Wigley | Technical EvangelistMatthias Shapiro | Program Manager / Technical Evangelist
Building Apps for Windows Phone 8.1Jump Start
Meet Andy Wigley | @andy_wigley • Technical Evangelist in Microsoft Developer
Experience and Evangelism (DX)• Mobile developer for over a decade, worked with WAP, ASP.NET Mobile
Controls, Windows Mobile and Windows Phone• Co-presenter of Windows Phone Jump Start for versions 7.0, 7.1, 8 and now 8.1
• Writer, Teacher and Presenter • Blog at http://andywigley.com • Written a number of books for Microsoft Press, including Mobile Development
Handbook (don’t buy, unless you’re working with .NET Compact Framework on Windows Mobile/CE!)
• Frequent speaker at industry conferences on all topics mobile• Rock-star (well, I play in a small – but popular – band )
Meet Matthias Shapiro | @matthiasshap
• Program Manager, Microsoft• Windows Phone Developer and Evangelist• Long-time XAML developer, from WPF to Silverlight to Windows Phone
• Windows Phone Demo-Writer and Noise-Maker (blog, Twitter)• Bigger bloggy things - http://blogs.msdn.com/b/matthiasshapiro/ • Code snippets – http://codeiuse.tumblr.com
Course Topics
Building Apps for Windows Phone 8.101 | Introducing the Windows Phone 8.1 App Development Platform
06 | Adapting UI for Different Screens and Orientations
02 | Getting Started Building Windows Runtime Apps
07 | Windows Runtime App Lifecycle
03 | Page Navigation and Data Binding in Windows Runtime Apps
08 | Localization and Globalization in
Windows Runtime Apps
04 | Lists and List Items in Windows Runtime Apps
09 | Data Storage, Backup and Roaming
05 | Programming Page Controls and Page Transition Animations
10 | Sharing Files and Data in Windows Phone 8.1
Course Topics
Building Apps for Windows Phone 8.1
11 | Background Tasks and Multitasking
16 | Interacting with User Data: Contacts and Appointments
12 | Maps, Geolocation and Geofencing
17 | Camera, Media and Audio in Windows Phone 8.1
13 | Networking, Mobile Services and
Authentication
18 | Enterprise in Windows Phone 8.1
14 | Tiles, Notifications and Action Center
19 | Programming SQLite on Windows Phone 8.1
15 | Sensors and Proximity: NFC and Bluetooth
20 | Tooling and Diagnostics
Course Topics
Building Apps for Windows Phone 8.121 | App packaging, monetization and publication
22 | Best practices: Building Universal Apps for Windows and Windows Phone
23 | Silverlight apps on Windows Phone 8.1
Andy Wigley @andy_wigleyMatthias Shapiro @matthiasshap
Background Tasks and Multitasking
Windows XAML+
Silverlight 8.1
30 April 2014
Building Apps for Windows Phone 8.1 Jump Start
In this module…
Multitasking on Windows PhoneProgramming background tasksBackground tasks run in response to triggersConditions on background task executionPush notifications trigger example
Mobile multitasking model
Apps not on screen are suspended
However apps can provide real-time content even when suspended
1. Live tiles or toasts2. Scheduled toasts and notifications 3. OS brokered tasks4. Background tasks and agents
Scheduled Task
PeriodicTask, ResourceIntensiveTask
Background Transfer Service
Background Location Tracking
VOIP and Audio Agents
Background Execution in WP8
Windows Phone 8.1 Background Tasks
Background tasks
An app can register background tasksTasks are scheduled and run by the OS, but are background ‘extensions’ of the foreground app
Same permissions from manifest, same storage, same file access, etc.Resource usage is constrained by the systemForeground app (if running) has limited communications with its tasks
Tasks can fire progress/completed events into the foreground appTasks can read/write the same storage as the foreground app
Tasks can use toast, tile, badge UI
An app’s existing task registrations can be queried from the systemAn app can have more than one background task
Creating a background task in your solutionAdd a new project to your solutionUse the Windows Runtime Component template
In your foreground app project, add reference to the Background Task project
Writing a background task
Background Task infrastructure can send a Cancelation notification if task is idle or not responding, but if memory cap is exceeded, task can be terminated without notification. Your task needs to be resilient to rude terminations without a Canceled event firing.
You register background asks to run in response to triggers firing
Tasks run in response to triggersTrigger Notes
System Trigger Runs on a specified system event.Events: UserPresent/Away, NetworkStateChange, InternetAvailable, SessionConnected, ServicingComplete, TimeZoneChange Note: LockScreenApplicationAdded and LockScreenApplicationRemoved are not supported on Windows Phone
TimeTrigger Runs on a frequency (minimum gap of 30 minutes)
LocationTrigger Runs as user enters/leaves a geofenced location
MaintenanceTrigger Runs on a frequency (minimum gap of 30 minutes)but only when the device is on AC power
PushNotificationTrigger Runs in response to an incoming raw push notification sent to the app.
Tasks run in response to triggersTrigger Notes
RfcommConnectionTrigger Bluetooth: when an RFCOMM connection has been established.
DeviceChangeTrigger Bluetooth: when an ACL connection has been created/destroyed.
BluetoothSignalStrengthTrigger Bluetooth: when signal strength goes outside of bounds.
GattCharacteristicNotificationTrigger
Bluetooth: when a characteristic change is received from a Bluetooth LE device
Note: ControlChannelTrigger, used on Windows to hold open a TCP/IP channel and trigger on incoming data, is not supported on Windows Phone
Conditions
ConditionUser[Not]PresentInternet[Not]AvailableFreeNetworkAvailableBackgroundWorkCostNotHigh
“run this task every 30 minutes if the internet is available”
Registration needs manifest entry
should not have to specify an executable for the background task host here.
Requesting background task access
Requesting background task access
async void RegisterBackgroundTasks() { // On Windows, RequestAccessAsync presents the user with a confirmation // dialog that requests that an app be allowed on the lock screen. // On Windows Phone, RequestAccessAsync does not show any user confirmation UI // but *must* be called before registering any tasks var access = await BackgroundExecutionManager.RequestAccessAsync();
// A 'good' status return on Phone is BackgroundAccess.AllowedMayUseActiveRealTimeConnectivity if (access == BackgroundAccessStatus.Denied) { // Either the user has explicitly denied background execution for this app // or the maximum number of background apps across the system has been reached // Display some informative message to the user... } }
New in Windows Phone 8.1
Sort and manage which apps can execute in the background
Controls number of apps that can run in the background
Battery Saver
Registering a background task
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder(); taskBuilder.Name = "MyBackgroundTask";
// Many different trigger types could be used here SystemTrigger trigger = new SystemTrigger(SystemTriggerType.TimeZoneChange, false); taskBuilder.SetTrigger(trigger); taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
// Entry point is the full name of our IBackgroundTask implementation // Good practice to use reflection as here to ensure correct name taskBuilder.TaskEntryPoint = typeof(MyBackgroundTask.TheTask).FullName;
BackgroundTaskRegistration registration = taskBuilder.Register();
// Optionally, handle the progress/completed events of the task registration.Progress += registration_Progress; registration.Completed += registration_Completed;
Querying task registrations
// AllTasks is a dictionary <Guid, IBackgroundTaskRegistration> so you can get back // to your registration by id or by posiiton, or select First if you only have one registration. var taskRegistration = BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault();
// We could then unregister the task, optionally cancelling any running instance if (taskRegistration != null) { taskRegistration.Unregister(true); }
// Release the progress/completed event subscriptions registration.Progress -= registration_Progress; registration.Completed -= registration_Completed;
Debugger can launch tasks
You can manually invoke your background task code using the debugger (once the registration code has been run)
Background tasks demo
Example: push notification trigger
Push notification triggers
Football ScoreCloud
Service
Windows Notification
Service
PushBackground
TaskStorage
0:32m Man City 1 Man Utd 0
0:47m Man City 1 Man Utd 1
0:85m Man City 2 Man Utd 1
End: Man City 2 Man Utd 1
<?xml version=“1.0”> Type = raw, Data = Man City....</xml>
123
Football News: Your Team Won!
4
<?xml version=“1.0”> Type = raw, Data = End Game</xml>
<?xml version=“1.0”> Type = raw, Data = Man City....</xml>
<?xml version=“1.0”> Type = raw, Data = Man City....</xml>
ForegroundApp
Push Notifications trigger
demo
Resource constraints
Resource constraints
All background tasks have CPU, memory and network quotasQuotas are based on actual CPU usage instead of wall clock time limits only. On Windows Phone, CPU usage quota is 2 seconds per app, refreshed every 15 minutes.Wall-clock CPU quota will also be enforced (at least 30 secs)Memory quota scales based on device capabilitiesTimeTrigger will have a 30 min floor on Phone
Call RequestAccessAsync() to get your full quota!
On 512MB devices, number of background apps is limitedIf exceeded, call to RequestAccessAsync will return Denied
Memory Caps in MB
Background task type 512 MB 1 GB 2 GB or greater
Location 16 30 40
Bluetooth 16 16 16
Servicing Complete 10 10 10
Other background tasks 16 30 40
Limit while debugging 30 40 50
Not supported in Windows Phone Store Apps
Apps that run under the lock-screen
Continuous background location tracking apps
VoIP agent (incoming call, progress etc.)
Foreground agents (WalletAgent)
Related topicsBackground audio See Session 17: Camera, Media and Audio
Background file transfer service See Session 13: Networking and Mobile Services
Notification mechanisms See Session 10: Tiles, badges and toasts and Notification Center
©2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and 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. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.