building universal apps for windows 10 devices · systemnavigationmanager windows.ui.core class for...

Post on 14-Jul-2020

2 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Building Universal Apps for Windows 10 Devices

Jeff Prosise

jeffpro@wintellect.com

Universal Windows Platform (UWP)

One API for all devices

Guaranteed core API layer across a wide

range of devices

Device families add their own unique

APIs to the guaranteed core API layer

Additional APIs exposed through

extension SDKs

One app package (binary) for all

devices

One Windows Store for all apps

and devices (even Win32 apps)

Your First Universal Windows Platform (UWP) App

App Structure

Application class derivative represents the app

Derived by Visual Studio in App.xaml and App.xaml.cs

Virtual OnLaunched method called at startup

Window.Current contains reference to app's window

Frame class serves as container for pages and provides navigation API

Override Application.OnLaunched to create a Frame instance and assign it to Window.Current.Content

Page class derivatives represent individual pages

Use "Add New Item" command in Visual Studio to add pages as needed

Optionally override virtual OnNavigatedTo and OnNavigatedFrom methods

Use OnNavigatedTo to retrieve parameters passed to pages when they're navigated to

Use Page.NavigationCacheMode property to control page persistence

Initializing the App

// In App.xaml.csprotected override void OnLaunched(LaunchActivatedEventArgs e){

Frame rootFrame = Window.Current.Content as Frame;

if (rootFrame == null){

rootFrame = new Frame();Window.Current.Content = rootFrame;

}

if (rootFrame.Content == null)rootFrame.Navigate(typeof(MainPage), e.Arguments);

Window.Current.Activate();}

Navigating to Another Page

// Navigate to DetailPage without passing datathis.Frame.Navigate(typeof(DetailPage));

// Navigate to DetailPage and pass datathis.Frame.Navigate(typeof(DetailPage), id);

Typed as Object, but always pass strings

Overriding OnNavigatedTo and OnNavigatedFrom

protected override void OnNavigatedTo(NavigationEventArgs e){

base.OnNavigatedTo(e);var parameter = e.Parameter; // Parameter passed in Navigate's second parameter

// TODO: Do anything necessary to initialize the page each time it's displayed}

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e){

base.OnNavigatingFrom(e);

// TODO: Do anything necessary to clean up before the user navigates// to another page

}

Going Backward and Forward

// Go backif (this.Frame.CanGoBack)

this.Frame.GoBack();

// Go forwardif (this.Frame.CanGoForward)

this.Frame.GoForward();

SystemNavigationManager

Windows.UI.Core class for handling back-navigation events without adding

extension SDKs or writing adaptive code

GetForCurrentView method returns reference to SystemNavigationManager instance

AppViewBackButtonVisibility property controls visibility of system-provided Back button

In window title bar on desktop apps

No effect on phone apps

BackRequested event fires when Back button is clicked

Software Back button in desktop apps

Hardware Back button in phone apps

Use it in individual pages, or provide global implementation in App.xaml.cs

Handling the Back Button

SystemNavigationManager.GetForCurrentView().BackRequested += (s, e) =>{

if (this.Frame.CanGoBack){

e.Handled = true;this.Frame.GoBack();

}};

Displaying a Back Button on Non-Mobile Devices

SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =AppViewBackButtonVisibility.Visible;

SystemNavigationManager

UWP Controls

Universal Windows Platform includes

numerous controls designed to work with

various types of input and present well

on a variety of screens and devices

Pseudo-controls (derive from class other than

control)

Controls (derive from Control)

Content controls (derive from ContentControl)

Items controls (derive from ItemsControl)

One UI, many devices

SplitView Control

"Hamburger" menu control

featured in many built-in apps

DisplayMode property controls layout

Inline

Overlay

CompactInline

CompactOverlay

IsPaneOpen opens and closes pane

Intended as quick-navigation aid

No default UI

DisplayMode="CompactInline | Overlay", IsPaneOpen="False"

DisplayMode="CompactInline", IsPaneOpen="True"

DisplayMode="CompactOverlay", IsPaneOpen="True"

Using SplitView

<SplitView DisplayMode="CompactOverlay" IsPaneOpen="False"CompactPaneLength="48" OpenPaneLength="200" PaneBackground="#C33D27">

<SplitView.Pane><!-- Declare menu items, including "hamburger," here -->

</SplitView.Pane>

<SplitView.Content><!-- Declare SplitView content here, or insert Frame in App.xaml.cs -->

</SplitView.Content>

</SplitView>

SplitView Controls

Adaptive UIs

UWP apps adapt their UIs to the screens they're running on

UWP provides state triggers and other tools for building adaptive UIs

State Triggers

Used with Visual State Manager to trigger changes in the UI

Visual State Manager updated to support setters

No more having to describe state changes with animations

UWP preview contains one state trigger: AdaptiveTrigger

Triggers changes based on window/screen width

Triggers changes based on window/screen height

Custom triggers are easily written by deriving from StateTriggerBase

Orientation triggers, device-family triggers, and many more

Using AdaptiveTrigger

<VisualState x:Name="WideState"><VisualState.StateTriggers><AdaptiveTrigger MinWindowWidth="600" />

</VisualState.StateTriggers><VisualState.Setters><Setter Target="LayoutRoot.Background" Value="LightYellow" />

</VisualState.Setters></VisualState><VisualState x:Name="NarrowState"><VisualState.StateTriggers><AdaptiveTrigger MinWindowWidth="0" />

</VisualState.StateTriggers><VisualState.Setters><Setter Target="LayoutRoot.Background" Value="LightGreen" />

</VisualState.Setters></VisualState>

Adaptive Triggers

Per-Device-Family Views

Views that are specific to device families

Views are XAML files without code-behind files

Use Add New Item -> XAML View in Visual Studio

Views reside in specially named folders which currently

must be created manually

DeviceFamily-Desktop for desktop apps

DeviceFamily-Mobile for mobile apps

One code-behind file, multiple views

The ultimate in adaptive UIs

Per-Device Family Views

HttpClient

Windows.Web.Http class for HTTP networking

Supercedes Windows 8's System.Net.Http.HttpClient class

Fetch content from the Web, call REST services, and more

Supports GET, POST, PUT, and DELETE

Supports chainable request filters

Supports progress events

Supports HTTPS

No cross-domain/cross-origin restrictions

Calling a REST Service

var client = new HttpClient();var response = await client.GetAsync(new Uri("..."));

if (response.IsSuccessStatusCode){

// Assumes response contains a string (e.g., JSON)var result = await response.Content.ReadAsStringAsync();

}

Specifying a Time-Out

var cts = new CancellationTokenSource();cts.CancelAfter(5000); // Wait up to 5 seconds

try{

var client = new HttpClient();var response =

await client.GetAsync(new Uri("...")).AsTask(cts.Token);}catch(OperationCanceledException){

// Operation timed out}

POSTing JSON to a REST Service

var json = "{\"firstName\":\"Bill\",\"lastName\":\"Gates\"}";

var client = new HttpClient();var content = new HttpStringContent(json);content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");var response = await client.PostAsync(new Uri("..."), content);

if (response.IsSuccessStatusCode){

// Assumes response contains a string (e.g., JSON)var result = await response.Content.ReadAsStringAsync();

}

WebAuthenticationBroker

Windows.Security.Authentication.Web class that enables seamless authentication

with online identity providers

AuthenticateAsync method authenticates with remote provider

Displays provider's login UI unless told not to

Supports OAuth and OpenID protocols

Amazon, Dropbox, Evernote, Facebook, Flickr, FourSquare, GitHub, Google, Instagram, LinkedIn, Reddit,

Tumblr, Twitter, Yammer, and many others

Allows app to gain access to secure sites without having to solicit, transmit, or

cache login credentials

Authentication token can be saved for future access

Consuming REST Services

UWP App Lifecycle

UWP apps not in the foreground are suspended

On a phone, suspension occurs when the user switches away from the app

On a desktop device, suspension occurs when the app is minimized

Application.Suspending event precedes suspension

Suspended apps can be terminated at any time

e.g., system needs the memory the app consumes

If reactivated, a terminated app should appear as if it was not terminated

Save state before app is suspended and restore it when app is reactivated

Use LocalFolder, LocalSettings, or both to persist state

Handling Application.Suspending Events

// In App.xaml.cspublic App(){

this.InitializeComponent();this.Suspending += this.OnSuspending;

}

private void OnSuspending(object sender, SuspendingEventArgs e){

var deferral = e.SuspendingOperation.GetDeferral();// TODO: Save state, using async methods if neededdeferral.Complete();

}

Determining Whether an App was Suspended and Terminated

// In the OnLaunched override in App.xaml.csif (e.PreviousExecutionState == ApplicationExecutionState.Terminated){

// TODO: Restore state saved when previous app instance was suspended}

Navigation State

In multipage apps, navigation state should be preserved

Return user to page they were on before suspension and termination

Restore the back stack to the state it was in before suspension and termination

Frame object tracks the navigation state and provides API for getting and setting it

Frame.GetNavigationState method returns serialized string containing current navigation state

Frame.SetNavigationState accepts serialized string containing navigation state

Persist the current navigation state in response to Application.Suspending events

Restore the navigation state in Application.OnLaunched if app was suspended and

terminated

Saving Navigation State

// In App.xaml.cspublic App(){

this.InitializeComponent();this.Suspending += this.OnSuspending;

}

private void OnSuspending(object sender, SuspendingEventArgs e){

Frame rootFrame = Window.Current.Content as Frame;ApplicationData.Current.LocalSettings.Values["NavState"] =

rootFrame.GetNavigationState();}

Restoring Navigation State

// In the OnLaunched override in App.xaml.csif (e.PreviousExecutionState == ApplicationExecutionState.Terminated){

if (ApplicationData.Current.LocalSettings.Values.ContainsKey("NavState")){

string navstate = (string)ApplicationData.Current.LocalSettings.Values["NavState"];rootFrame.SetNavigationState(navstate);

}}else{

ApplicationData.Current.LocalSettings.Values.Clear();}

Preserving State

Adaptive Code

All devices implement all APIs in the Universal device family

Targeting other APIs (e.g., Mobile device family) requires adaptive code

if (ApiInformation.IsTypePresent("Windows.Phone.UI.HardwareButtons"){

Windows.Phone.UI.HardwareButtons.CameraPressed += (s, e) =>{

// TODO: Respond to presses of the phone's camera button};

}

Extension SDKs for Device Families

Core UWP APIs are available on all Windows 10 devices

Roughly 90% of all APIs available on Windows 10 devices

Additional APIs are made available by adding device-family extension SDKs

Microsoft Desktop Extension SDK for PCs

Microsoft Mobile Extension SDK for mobile devices (phones)

HoloLens, Xbox Live, IoT, and more

UWP apps adapt their code to the device families they're running on

UWP provides the APIs for doing so

Microsoft Desktop Extension SDK Assemblies (Partial List)

Windows.ApplicationModel.Calls.LockScreenCallsContract

Windows.ApplicationModel.Search.SearchContract

Windows.ApplicationModel.Wallet.WalletContract

Windows.Devices.Printers.PrintersContract

Windows.Devices.Scanners.ScannerDeviceContract

Windows.Devices.SmartCards.SmartCardDeviceContract

Windows.Security.ExchangeActiveSyncProvisioning.EasContract

Windows.System.UserProfile.UserProfileContract

Windows.Media.Capture.CameraCaptureUIContract

Microsoft Mobile Extension SDK Assemblies

Windows.ApplicationModel.Calls.CallsPhoneContract

Windows.ApplicationModel.Wallet.WalletContract

Windows.Devices.SmartCards.SmartCardBackgroundTriggerContract

Windows.Devices.SmartCards.SmartCardEmulatorContract

Windows.Phone.PhoneContract

Windows.Phone.StartScreen.DualSimTileContract

Windows.Security.ExchangeActiveSyncProvisioning.EasContract

Windows.System.UserProfile.UserProfileContract

Windows.UI.WebUI.Core.WebUICommandBarContract

{ Windows.ApplicationModel }

{ Windows.Media.Capture }

{ Windows.Media.Effects }

{ Windows.Media.SpeechRecognition }

{ Windows.Phone }

{ Windows.Phone.ApplicationModel }

{ Windows.Phone.Devices.Notification }

{ Windows.Phone.Devices.Power }

{ Windows.Phone.Media.Devices }

{ Windows.Phone.PersonalInformation }

{ Windows.Phone.Speech.Recognition }

{ Windows.Phone.System }

{ Windows.Phone.System.Power }

{ Windows.Phone.System.Profile }

{ Windows.Phone.UI.Input }

{ Windows.Phone.UI.ViewManagement }

...

Windows.Foundation.Metadata.ApiInformation

Static class for writing adaptive code via run-time API discovery

Method Description

IsApiContractPresent Indicates whether the specified contract is present on this device

IsEnumNamedValuePresent Indicates whether the specified value is present on a specified enum

IsEventPresent Indicates whether the specified event is present on the specified type

IsMethodPresent Indicates whether the specified method is present on the specified type

IsPropertyPresent Indicates whether the specified property is present on the specified type

IsReadOnlyPropertyPresent Indicates whether the specified read-only property is present on the specified type

IsTypePresent Indicates whether the specified type is present on this device

IsWriteablePropertyPresent Indicates whether the specified write-only property is present on the specified type

Using ApiInformation.IsApiContractPresent

if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.Calls.CallsPhoneContract")

{// TODO: Use Windows.ApplicationModel.Calls.CallsPhoneContract types and type members

}

Using ApiInformation.IsTypePresent

if (ApiInformation.IsTypePresent("Windows.Phone.UI.HardwareButtons"){

Windows.Phone.UI.HardwareButtons.BackPressed += (s, e) =>{

// TODO: Respond to the phone's hardware Back button};

}

top related