10 sharing files and data in windows phone 8
DESCRIPTION
Building Apps for Windows Phone 8.1 Jump Start . Videos at: http://channel9.msdn.com/Series/Building-Apps-for-Windows-Phone-8-1TRANSCRIPT
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
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
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
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.
File and Uri Associations
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"));
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") } );
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);
Registering File and/or Uri Associations (Target)
Windows Runtime Apps
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(); }
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 ... } } ... }
12
Demo
File and Uri Associations
13
Share Contract
14
Internal apps
Sharing isn’t New to Windows Phone
Silverlight 8 apps (ShareLinkTask/ShareStatusTask)
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
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.
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)
Share Contract UX
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
20
Implementing a Share Source
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
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.
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.
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
Sharing Source
demo
26
Implementing a Share Target
Registering as a Share TargetRegister supported formats and file types in the Manifest:Plain textFormatted textURIHTMLImagesFilesCustom data formats
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(); }
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; }
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(); }
33
Creating a Share Target
demo
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
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
36
Picker Contracts
37
• Silverlight 8 apps (PhotoChooserTask)
Pickers aren’t new to Windows Phone
WP 8.1 FileOpenPicker/FileSavePicker UX
Other apps…
Your app Provider selection (shell)
Provider UI Your app
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
40
File Picker Client App
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
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(); } }
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; } }
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
47
Using the picker contracts
demo
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
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
50
Windows.Storage.AccessCache
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
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
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 } }
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 ... } }
55
Access cache
demo
56
Summary
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
New Possibilities
©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.