apps are notified when they have been resumed

28
The story of state App data, settings, and the process lifecycle Kraig Brockschmidt Senior Program Manager, Windows Ecosystem Team Author, Programming Windows 8 Apps with HTML, CSS, and JavaScript 3-126

Upload: archibald-james

Post on 24-Dec-2015

222 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Apps are notified when they have been resumed

The story of stateApp data, settings, and the process lifecycle

Kraig BrockschmidtSenior Program Manager, Windows Ecosystem TeamAuthor, Programming Windows 8 Apps with HTML, CSS, and JavaScript3-126

Page 2: Apps are notified when they have been resumed

Look at stateful apps from the perspective of state itselfWhat is its purposeWhere does it liveWhat affects and modifies state

Agenda

Page 3: Apps are notified when they have been resumed

The purpose of state is to maintain a consistent app experience acrosssessions, devices, and process lifecycle events

Page 4: Apps are notified when they have been resumed

The user experience: apps are stateful

Apps don’t start in an uninitialized state, even on first runPersistent settings are always in effectSettings that are user-specific but not device-specific can roam across devices (like account setups)The settings charm is where users manage relevant stateTransient session state (like unsubmitted form data and navigation history) is preserved across sessions if and only if Windows terminates an appUser data is more app-independent

Page 5: Apps are notified when they have been resumed

State is persistent

State exists when apps aren’t running or in memory at allState carries user preferences across sessionsState carries transient session data across suspend, terminate, and restartState can roam across a user’s devicesState can be modified by background tasksState is versioned independently of apps (and less often)

Page 6: Apps are notified when they have been resumed

Review of process lifecycle events

Runningapp

Suspendedapp

SuspendingTerminatedapp

Low resources

Code gets to runApp frozen App not running

Resuming

App gets 5 seconds to

handle suspend

App is not notified before

termination

Apps are notified when they have been resumed

User launches app

Splash screen

Limited background tasks can run

Page 7: Apps are notified when they have been resumed

Demo

Stateful apps

Page 8: Apps are notified when they have been resumed

The big picture of state

In memory(app changes variables)

Running Suspended Not running System restart Other devices

Local/temp app data (modified by WinRT and other APIs)Includes databases (SQLite, IndexedDB, ESE/Jet) and other facilities built on appdata (HTML AppCache, local storage, third-party libraries)

Roaming app data (modified by WinRT and other APIs), sync’d to cloud (within quota)

Windows.Storage.AccessCache (modified by WinRT API)

Windows.Storage.PasswordVault (modified by WinRT API), sync’d to cloud

Page 9: Apps are notified when they have been resumed

Basic state settings (C#)using Windows.Storage;

// Create a simple settingApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;localSettings.Values["message"] = "Hello World";

Object value = localSettings.Values["message"];

// Create a setting in a containerApplicationDataContainer container = localSettings.CreateContainer( "exampleContainer", ApplicationDataCreateDisposition.Always);

localSettings.Containers["exampleContainer"].Values["message"] = "Hello World";Object value = localSettings.Containers["exampleContainer"].Values["message"];

Page 10: Apps are notified when they have been resumed

Basic files (C#)using Windows.Storage;

// Write a fileStorageFolder roamingFolder = ApplicationData.Current.roamingFolder;StorageFile file = await roamingFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

await FileIO.WriteTextAsync(file, counter.ToString());

// Read a fileStorageFile file = await roamingFolder.GetFileAsync(filename);string text = await FileIO.ReadTextAsync(file);

Page 11: Apps are notified when they have been resumed

Composite + HighPriority roaming (C#)using Windows.Storage;

ApplicationDataContainer roamingSettings = ApplicationData.Current.RoamingSettings;ApplicationDataCompositeValue composite = new ApplicationDataCompositeValue();

composite["readerSet"] = "Liam's Books";composite["page"] = 524;roamingSettings.Values["HighPriority"] = composite;

Page 12: Apps are notified when they have been resumed

DataChanged event (C#)using Windows.Storage;

// DataChanged is fired when new data has been roamed to this deviceapplicationData.DataChanged += new TypedEventHandler<ApplicationData, object> (DataChangedHandler);

async void DataChangedHandler(Windows.Storage.ApplicationData appData, object o){ // DataChangeHandler may be invoked on a background thread, so use the // Dispatcher to invoke the UI-related code on the UI thread. Not needed // in JavaScript. await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Handle new data });}

Page 13: Apps are notified when they have been resumed

Access cache (C#)using Windows.Storage;using Windows.Storage.AccessCache;

// First permission granted by folder pickerStorageFolder folder = await folderPicker.PickSingleFolderAsync();if (folder != null){ // Remember permission for future access to the folder // (including other sub-folder contents) StorageApplicationPermissions.FutureAccessList.AddOrReplace( "PickedFolderToken", folder);}

// Retrieve cached permission (in a later session)StorageFolder folder2 = await StorageApplicationPermissions.FutureAccessList .getFolderAsync("PickedFolderToken");

Page 14: Apps are notified when they have been resumed

Credential LockerFor securely storing passwords apps should neither store nor roam passwords independentlyOn trusted PCs, these are roamed with the userAlso note CredentialPicker APISample:http://bit.ly/OUr8LC

Page 15: Apps are notified when they have been resumed

Credential Picker & Locker (C#)using Windows.Security.Credentials;using Windows.Security.Credentials.UI;

CredentialPickerOptions credPickerOptions = new CredentialPickerOptions();// Set options like captions, messages, protocol, etc.var res = await CredentialPicker.PickAsync(credPickerOptions);

PasswordVault vault = new PasswordVault();

// Password typically encrypted already from UI...but this is good for plain textPasswordCredential c = new PasswordCredential("myCreds", res.CredentialUserName, res.CredentialPassword);vault.Add(c);

// To retrieve later onPasswordCredential cred = vault.Retrieve("myCreds", userName);

Page 16: Apps are notified when they have been resumed

Additional AppData APIsAll languagesSQLite: http://bit.ly/MuzL1e (Tim Heuer’s blog)ESE/Jet APIs (Win32): http://bit.ly/ToslcK (reference); for JavaScript needs a WinRT component

JavaScript onlyIndexedDB: http://bit.ly/RyT9uk (reference) http://bit.ly/P5H292 (sample)HTML5 localStorage: http://www.w3.org/TR/webstorage/ HTML5 AppCache: http://dev.w3.org/html5/spec/offline.html

Page 17: Apps are notified when they have been resumed

State versioningApplies to the entire contents of AppDataManaged through SetVersionAsyncNo relationship to app version: many app versions can and will likely use the same version of stateOn launch, app should migrate old state if found, and call SetVersionAsync to update the versionCloud service for roaming data maintains multiple versions until all apps have upgradedCan use ServicingComplete background task trigger to migrate state when an app update is installed

Page 18: Apps are notified when they have been resumed

Settings UISettings is a ubiquitous app feature, hence the charmSettings charm eliminates need to have specific settings pages within the app’s navigation hierarchyUse for state and configuration that the user can controlAccounts, preferences, etc.Specifying what roams and what doesn’t

State that app maintains silently doesn’t need to appear hereApp’s settings flyouts are just pieces of UI with unique means of invoking them; typically write to persistent state

Page 19: Apps are notified when they have been resumed

Settings APIApp responds to Windows.UI.ApplicationSettings.CommandsRequested eventApp populates commandsLinks: help, privacy statement, terms of use, etc.Panels: invoke flyouts that change app dataSystem provides permissions, rate and review

Settings flyout controlsXAML: Windows.UI.Xaml.Controls.SettingsFlyoutJavaScript: WinJS.UI.SettingsFlyout

Page 20: Apps are notified when they have been resumed

Demo

Settings

Page 21: Apps are notified when they have been resumed

Background tasks for stateMaintenance triggersRun periodically on AC powerUseful for cleaning up temp state

System triggersAC power, non-lock screenInternetAvailable, NetworkStateChange for connectivityServicingComplete: perfect time to migrate app state versions

Lock screen triggers (AC or battery power)Session Connected, UserPresent, UserAway, TimeTrigger

All tasks subject to CPU and network activity quotasIndependent of main app (can use mixed languages)

Page 22: Apps are notified when they have been resumed

Demo

Background tasks for state

Page 23: Apps are notified when they have been resumed

Best practices for appsLaunch with initial defaultsJavaScript: use sessionState object as a namespace for variablesC#/VB/C++: Use SuspensionManager helpers

Write session and persistent state incrementally as it changesDon’t leave this for the suspending event unless necessary

Always save file references in access cache—never save pathsSome files/folders don’t come from the file system!

Always save passwords in the Credential LockerUse encryption for security, compression to minimize size

Page 24: Apps are notified when they have been resumed

Best practices for appsSession state: restore if launched after terminatedTypically only a few pieces of data

Session state is not restored if app is launched to service contracts or launch argumentsException: searchLaunch arguments means file type activation or secondary tile

Check elapsed time and refresh when resumingEspecially data from online services

Page 25: Apps are notified when they have been resumed

• 10/31 145p – Kodiak – Introduction to creating Windows Store apps using XAML (3-116)

• 10/30 215p – Kodiak – Introduction to creating a Windows Store App using HTML and JavaScript (3-115)

• 11/1 830a – Kodiak – Alive with activity: Tiles, notifications, and background tasks (3-101)

Related sessions

Page 28: Apps are notified when they have been resumed

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