8. var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata://Local/mydoc.pdf"));
await Launcher.LaunchFileAsync(file);
8
9.
10. 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();
}
11. 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
...
}
}
...
}
21. 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
22. // 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());
}
Title
You 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.
23. // 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.
24. 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
39. 41
//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...
}
//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();
40. 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();
}
}
41. 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;
}
}
42. //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
...
//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();
49. 53
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
}
}
50. 54
// 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
...
}
}
53. 57
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