10 sharing files and data in windows phone 8

55
Andy Wigley @andy_wigley Matthias Shapiro @matthiasshap Sharing Files and Data in Windows Phone 8.1 WP8.1 Jump Start 29 April 2014 Building Apps for Windows Phone 8.1 Jump Start

description

Building Apps for Windows Phone 8.1 Jump Start . Videos at: http://channel9.msdn.com/Series/Building-Apps-for-Windows-Phone-8-1

Transcript of 10 sharing files and data in windows phone 8

Page 1: 10   sharing files and data in windows phone 8

Andy Wigley @andy_wigleyMatthias Shapiro @matthiasshap

Sharing Files and Data in Windows Phone 8.1

WP8.1 Jump Start

29 April 2014

Building Apps for Windows Phone 8.1 Jump Start

Page 2: 10   sharing files and data in windows phone 8

2

In this module…

App to app communication File AssociationsUri Associations

Sharing data with other appsMaking your app a Share sourceImplementing a Share target

Opening and Saving files with the File open and save pickersProgramming the File Open and File Save Pickers in your appImplementing File Open and File Save Provider capability in an app

Page 3: 10   sharing files and data in windows phone 8

Sharing in Windows Phone 8.1

Windows.System.Launcher.LaunchUriAsync( new Uri("jumpstart:NewSession?ID=aea6"));

Shell

Data in Uri

Uri association

Windows.System.Launcher.LaunchFileAsync( myStorageFile);

Data in File

File association

Windows.ApplicationModel.DataTransfer.DataTransferManager.ShowShareUI();

File, text, HTML, image, custom data in DataPackage

Share contractShare transient UI

Page 4: 10   sharing files and data in windows phone 8

Differences from WindowsOn Windows, user manages programs to launch for a file extension or protocol in the Set Associations settings

On Windows Phone, if more than one match, shell prompts user for the program to launch.

Windows Store Apps supports Share contract and Settings contract. Launched from Charms bar.

On Windows Phone, there is no Charms bar. Only Share contract is supported. App will implement its own UI for Settings.

Page 5: 10   sharing files and data in windows phone 8

File and Uri Associations

Page 6: 10   sharing files and data in windows phone 8

Custom URI Associations

Launch other apps to complete tasksLaunch another app and pass it dataPlay an album on SpotifyPlay a video in YouTubeLaunch device settings

Link into core experiencesBrowser (http)MessagingEmail (mailto:)

await Launcher.LaunchUriAsync(new Uri("fb://profile/1234"));

Page 7: 10   sharing files and data in windows phone 8

7

Custom URI Associations

What’s new?Added support for new LauncherOptionsFallbackUri

await Launcher.LaunchUriAsync( new Uri("fb://profile/1234"), new LauncherOptions { FallbackUri = new Uri("http://facebook.com/profile.php?id=1234") } );

Page 8: 10   sharing files and data in windows phone 8

8

File Type Associations

Launch files in the right appMicrosoft OfficeAdobe Reader

Handle custom files in your app fromAnother appBrowserEmailOffice Hub

var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata://Local/mydoc.pdf"));await Launcher.LaunchFileAsync(file);

Page 9: 10   sharing files and data in windows phone 8

Registering File and/or Uri Associations (Target)

Windows Runtime Apps

Page 10: 10   sharing files and data in windows phone 8

Handling File Activation (Windows Runtime Apps)

protected override async void OnFileActivated(FileActivatedEventArgs args) { // Handle file activation. The number of files received is args.Files.Size. First file is args.Files[0].Name

Frame rootFrame = Window.Current.Content as Frame;

... // Standard Frame initialization code ...

if (rootFrame.Content == null) { if (!rootFrame.Navigate(typeof(BugQueryPage))) { throw new Exception("Failed to create initial page"); }

}

var p = rootFrame.Content as BugQueryPage;

// Pass the File activation args to a property you’ve implemented on the target page p.FileEvent = args;

Window.Current.Activate(); }

Page 11: 10   sharing files and data in windows phone 8

Handling Uri Activation (Windows Runtime Apps)

public partial class App { ... protected override void OnActivated(IActivatedEventArgs args) { if (args.Kind == ActivationKind.Protocol) { ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;

// TODO: Handle URI activation // The received URI is eventArgs.Uri.AbsoluteUri ... } } ... }

Page 12: 10   sharing files and data in windows phone 8

12

Demo

File and Uri Associations

Page 13: 10   sharing files and data in windows phone 8

13

Share Contract

Page 14: 10   sharing files and data in windows phone 8

14

Internal apps

Sharing isn’t New to Windows Phone

Silverlight 8 apps (ShareLinkTask/ShareStatusTask)

Page 15: 10   sharing files and data in windows phone 8

15

Windows 8.1 Share Contract Extends SharingEnable user-driven sharing between appsApps can freely share content from Source to TargetNo distinctions between 1st and 3rd party capabilitiesNo limitations on content type

Works well on low-cost devicesAvailable for Windows XAML and Silverlight 8.1 apps

Many apps will be Share sourceMost apps have something worth sharing

Only a few apps will be a Share target

Page 16: 10   sharing files and data in windows phone 8

Share Source and Share Target

Share SourceUsing this contract tells Windows that your app can provide data (files, text, images, more) to other apps. Many apps will be a share source.

Share TargetImplementing share target means that your app can be on the receiving end of data from other apps. Relatively few apps will be share target.

Helps centralize the interface to a potentially volatile back-endAn email or social networking app could receive images and text from any other app, and thereby serve as the primary interface for that social network. Other apps do not need to understand the protocols or APIs just to send information.

Page 17: 10   sharing files and data in windows phone 8

Integration with Built-In SharingBuilt-In Sources• Single Photo Viewer

(Photos)• IE (Web pages)• Xbox Music (Music/video

URI)• Office (Documents)• Contacts (vcard file)

Built-In Targets• Email (text/URI/files)• Messaging (text/URI)• Tap+Send (URI/files)• Bluetooth (files)• OneNote

(text/URI/pictures)• Rooms (files)

Page 18: 10   sharing files and data in windows phone 8

Share Contract UX

Page 19: 10   sharing files and data in windows phone 8

Sharing From Source to TargetSource app Share target appShare picker (Shell)

User selects “Share” charm (Windows)

Activated for sharing

Registers with the DataTransfer

Manager

Filters list of Target Apps

User selects Target App

Processes DataPackage contents

Reports Complete

Completes Async calls and returns

Receives event and fills DataPackage

DataPackage lives in source application

Activate Target as kind shareTarget

User selects “Share” UI (Windows Phone)

Active app is sent event

Page 20: 10   sharing files and data in windows phone 8

20

Implementing a Share Source

Page 21: 10   sharing files and data in windows phone 8

Implementing share source

protected override void OnNavigatedTo(NavigationEventArgs e) { navigationHelper.OnNavigatedTo(e); DataTransferManager.GetForCurrentView().DataRequested += OnShareDataRequested; } protected override void OnNavigatedFrom(NavigationEventArgs e) { navigationHelper.OnNavigatedFrom(e); DataTransferManager.GetForCurrentView().DataRequested -= OnShareDataRequested; }

private void AppBarButton_Click(object sender, RoutedEventArgs e) { DataTransferManager.ShowShareUI(); } ! Always remove your event handlers

Always tear down your event handlers when you’re done with them

Page 22: 10   sharing files and data in windows phone 8

Implementing share source

// Handle DataRequested event and provide DataPackage void OnShareDataRequested(DataTransferManager sender, DataRequestedEventArgs args) { var request = args.Request;

request.Data.Properties.Title = "Share example"; //You MUST set a Title! request.Data.Properties.Description = "This demonstrates how to share text to another app"; request.Data.SetText(TextToShare.Text.Trim()); }

TitleYou must set a Title on the Data Package. If you do not, the Share operation silently fails (no exception).

Description

Not used by the Share UI on Windows Phone (used by the Windows Share UI), but is available to the Share target.

Page 23: 10   sharing files and data in windows phone 8

Including Files in Data Package

// Handle DataRequested event and provide DataPackage async void OnShareDataRequested(DataTransferManager sender, DataRequestedEventArgs args) { var dp = args.Request.Data; var deferral = args.Request.GetDeferral(); var photoFile = await StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appx:///Assets/needle.jpg"));

dp.Properties.Title = "Space Needle"; dp.Properties.Description = "The Space Needle in Seattle, WA"; dp.SetStorageItems(new List<StorageFile> { photoFile }); dp.SetWebLink(new Uri("http://seattletimes.com/ABPub/2006/01/10/2002732410.jpg")); deferral.Complete(); } Deferrals

You need to use deferrals when there is an async operation in the request.

Page 24: 10   sharing files and data in windows phone 8

Data Package Data Formats

Method Comments

SetApplicationLink(Uri value) A Uri back to the source application (a Uri association)

SetBitmap(RandomAccessStreamReference value)

A bitmap image

SetData(string formatId, object value) Used in a delayed rendering callback method to supply the data

SetDataProvider(string formatId, DataProviderHandler delayRenderer)

Declares a callback method for delayed rendering of data items, if acquisition of data for sharing is time-consuming

SetHtmlFormat(string value) HTML content

SetRtf(string value) RTF formatted text

SetStorageItems(IEnumerable<IStorageItem> value, bool readOnly)

One or more files and/or folders

SetText(string value) Simple text

SetWebLink(Uri value) Link to a resource on the network

Page 25: 10   sharing files and data in windows phone 8

Sharing Source

demo

Page 26: 10   sharing files and data in windows phone 8

26

Implementing a Share Target

Page 27: 10   sharing files and data in windows phone 8

Registering as a Share TargetRegister supported formats and file types in the Manifest:Plain textFormatted textURIHTMLImagesFilesCustom data formats

Page 28: 10   sharing files and data in windows phone 8

Share Target Activation (Windows Runtime Apps)

// Override OnShareTargetActivated and redirect user to sharing page protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame;

if (rootFrame == null) { rootFrame = new Frame(); Window.Current.Content = rootFrame; }

if (rootFrame.Content == null) rootFrame.Navigate(typeof(SharePage), args.ShareOperation);

Window.Current.Activate(); }

Page 29: 10   sharing files and data in windows phone 8

31

Acting as a Share Target (Windows Runtime App + Silverlight)

// This code in the transient UI (Share target page) handles the Data Package. protected override async void OnNavigatedTo(NavigationEventArgs e) { shareOp = e.Parameter as ShareOperation;

TitleTextBlock.Text = shareOp.Data.Properties.Title; DescriptionTextBlock.Text = shareOp.Data.Properties.Description; SharedTextTextBlock.Text = await shareOp.Data.GetTextAsync();

var photoFile = (StorageFile)(await shareOp.Data.GetStorageItemsAsync())[0]; var imageSource = new BitmapImage(); imageSource.SetSource(await photoFile.OpenReadAsync());

sharedPhotoImage.Source = imageSource; }

Page 30: 10   sharing files and data in windows phone 8

32

Acting as a Share Target

// Call ReportCompleted when done to return user to source app private void Button_Click(object sender, RoutedEventArgs e) { shareOp.ReportCompleted(); }

Page 31: 10   sharing files and data in windows phone 8

33

Creating a Share Target

demo

Page 32: 10   sharing files and data in windows phone 8

34

Sources• Share multiple formats of your content (if possible)• Use ApplicationLink/WebLink rather than URI

Targets• Keep sharing UX self-contained – no Home button!• Hand off large uploads to the Background Transfer API• Always call ReportCompleted to send the user back to where they came from

Sharing Best Practices

Page 33: 10   sharing files and data in windows phone 8

35

Complete API convergence

Phone-specific behavior• No long running shares – Share Target is transient and is not kept alive• We do not support Quicklinks• Source application will be suspended when Share is invoked• Source application may be terminated while Share is running

Share contract comparison with Windows

Page 34: 10   sharing files and data in windows phone 8

36

Picker Contracts

Page 35: 10   sharing files and data in windows phone 8

37

• Silverlight 8 apps (PhotoChooserTask)

Pickers aren’t new to Windows Phone

Page 36: 10   sharing files and data in windows phone 8

WP 8.1 FileOpenPicker/FileSavePicker UX

Other apps…

Your app Provider selection (shell)

Provider UI Your app

Page 37: 10   sharing files and data in windows phone 8

Picker GoalsApps shouldn’t care where files come from or go toApps can access any type of fileAllows an app to access files that are not in the app data foldersAccess files in Pictures Library, Videos Library without KnownFolders API needing Capability declaration – permission is implied since the user selects the fileSeamlessly go out to the cloud, phone or an app to get a file

Support both Open and SaveSave to the cloud, phone or an appUpdate latest changes as required (handled by the provider)

Work well on low-cost devicesAvailable for Windows XAML and Silverlight 8.1

Page 38: 10   sharing files and data in windows phone 8

40

File Picker Client App

Page 39: 10   sharing files and data in windows phone 8

41

Picker Contracts – Pick a FileUsage Differs on Windows and Windows Phone

//Create the picker object FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

// Users expect to have a filtered view of their folders openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".png");

// Open the picker for the user to pick a file StorageFile file = await openPicker.PickSingleFileAsync();

if (file != null) { // Do something with the file...}

Windows

//Create the picker object FileOpenPicker openPicker = new FileOpenPicker();

// Users expect to have a filtered view of their folders openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".png");

// Open the picker for the user to pick a file openPicker.ContinuationData["Operation"] = "SomeDataOrOther"; openPicker.PickSingleFileAndContinue();

Windows Phone

App suspended, may be terminated

App activated when file picked

Page 40: 10   sharing files and data in windows phone 8

Activation after File Picker (Windows Runtime Apps)1 of 2 – App.xaml.cs protected override async void OnActivated(IActivatedEventArgs args) { if (args is FileOpenPickerContinuationEventArgs) { Frame rootFrame = Window.Current.Content as Frame;

... // Standard Frame initialization code ...

if (!rootFrame.Navigate(typeof(ProfilePage))) { throw new Exception("Failed to create target page"); }

var p = rootFrame.Content as ProfilePage; p.FilePickerEvent = (FileOpenPickerContinuationEventArgs)args;

// Ensure the current window is active Window.Current.Activate(); } }

Page 41: 10   sharing files and data in windows phone 8

Activation after File Picker (Windows Runtime Apps)2 of 2 – Page where picker was initiated private FileOpenPickerContinuationEventArgs _filePickerEventArgs = null; public FileOpenPickerContinuationEventArgs FilePickerEvent { get { return _filePickerEventArgs; } set { _filePickerEventArgs = value; ContinueFileOpenPicker(_filePickerEventArgs); } }

public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args) { if ((args.ContinuationData["Operation"] as string) == "SomeDataOrOther" && args.Files != null && args.Files.Count > 0) { StorageFile file = args.Files[0]; IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(fileStream); ProfilePic.Source = bitmapImage; } }

Page 42: 10   sharing files and data in windows phone 8

Picker Contracts – Save a FileUsage Differs on Windows and Windows Phone

//Create the picker object FileSavePicker savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;

// Dropdown of file types the user can save the file as    savePicker.FileTypeChoices.Add( "Plain Text", new List<string>() { ".txt" }); // Default file name if the user does not type one in or select// a file to replace

savePicker.SuggestedFileName = "New Document";

// Open the picker for the user to select the target file StorageFile file = await openPicker.PickSaveFileAsync();

// Save the content to the file ...

Windows

//Create the picker object FileSavePicker savePicker = new FileSavePicker();

// Dropdown of file types the user can save the file as    savePicker.FileTypeChoices.Add( "Plain Text", new List<string>() { ".txt" }); // Default file name if the user does not type one in or select // a file to replace

savePicker.SuggestedFileName = "New Document";

// Open the picker for the user to pick a file savePicker.ContinuationData["Operation"] = "SomeDataOrOther"; savePicker.PickSingleFileAndContinue();

Windows Phone

App suspended, may be terminated

App activated when file picked

Page 43: 10   sharing files and data in windows phone 8

47

Using the picker contracts

demo

Page 44: 10   sharing files and data in windows phone 8

48

Different APIs on Windows 8.1 and Windows Phone 8.1

• Resulting from requirement to support low memory devices

Phone-specific behavior• SuggestedStartLocation is ignored• ViewMode is ignored• FileNameChanged event is not fired• Title is ignored

File Open/Save Picker Comparison with Windows

Page 45: 10   sharing files and data in windows phone 8

49

File Picker Provider apps

Similar to Share Target apps, you can create apps that will be listed in the shell Picker UI that the user can select to pick files that that app controls, or to save new filesExample: OneDrive app is a picker provider that allows users to pick and save files in their OneDrive account in the cloud

Available for Windows Runtime and Windows Phone Silverlight 8.1See MSDN documentation for further details

Page 46: 10   sharing files and data in windows phone 8

50

Windows.Storage.AccessCache

Page 47: 10   sharing files and data in windows phone 8

51

What is AccessCache?Imagine an app that uses the File pickers to open and save files at any locationWhat if the user wants to reopen a file he or she edited last week?Do we need to show the picker and get the user to open the file again?

We need a way to store references to files and folders and their permissions so that the user can reopen them with one tapThat way is through Windows.Storage.AccessCache.StorageApplicationPermissions

Page 48: 10   sharing files and data in windows phone 8

52

FutureAccessList and MostRecentlyUsedListAll apps have a FutureAccessList and a MostRecentlyUsedList (MRU)The MRU is a list you can use to track the files and folders your user accesses frequently25-item limit, automatically managed so oldest item automatically removed when limit is reached

FutureAccessList is a list you can use to store files and/or locations (like folders) and easily access them in the future1000-item limit, but not automatically managed, so you must remove items when limit is reachedIf File or Folder is later moved, FutureAccessList tracks it automatically, maintaining access in the future

When a user picks a file or folder, you should consider adding that item to both the MRU and the FutureAccessList

Page 49: 10   sharing files and data in windows phone 8

53

Usage – Saving in the AccessCache

public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args) { if ((args.Files != null && args.Files.Count > 0) { StorageFile file = args.Files[0]; // Save the picked file in the AccessCache // Add to MRU with metadata (For example, a string that represents the date) string mruToken = StorageApplicationPermissions.MostRecentlyUsedList.Add(file, "20120716"); // Add to FA without metadata string faToken = StorageApplicationPermissions.FutureAccessList.Add(file); } else { // The file picker was dismissed with no file selected to save } }

Page 50: 10   sharing files and data in windows phone 8

54

Usage – Retrieving from the Access Cache

// get the token for the first item in our MRU and use it to retrieve a StorageFile that represents that file

String mruFirstToken = StorageApplicationPermissions.MostRecentlyUsedList.Entries.First().Token; StorageFile retrievedFile = await StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(mruFirstToken);

...

// Retrieve tokens for all items in the MRU AccessListEntryView mruEntries = StorageApplicationPermissions.MostRecentlyUsedList.Entries; if (mruEntries.Count > 0) { foreach (AccessListEntry entry in mruEntries) { String mruToken = entry.Token; // Continue processing the MRU entry ... } }

Page 51: 10   sharing files and data in windows phone 8

55

Access cache

demo

Page 52: 10   sharing files and data in windows phone 8

56

Summary

Page 53: 10   sharing files and data in windows phone 8

57

Adding it all up

Windows Phone 8 Windows Phone 8.1 Windows 8.1

File associations Yes Yes Yes

URI contracts Yes Yes Yes

Share Limited Yes Yes

File open picker No Yes Yes

File save picker No Yes Yes

Page 54: 10   sharing files and data in windows phone 8

New Possibilities

Page 55: 10   sharing files and data in windows phone 8

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