First of all, we recommend a UWP/WIN10 developer base: 53078485 There are many aunt, there are a lot of learning resources, welcome to discuss the development of WIN10!
In UWP development, Microsoft offers a new feature called Sharedstorageaccessmanager, which allows our app to generate a filetoken to share this file based on the specified file. Other apps can use Sharedstorageaccessmanager. Redeemtokenforfileasync (Filetoken); method gets the shared file according to the Filetoken. This provides the ability to share files between two apps.
Let's start by looking at what APIs are available in the Sharedstorageaccessmanager class for us to use:
Method |
Describe |
AddFile |
Gets a file share token that enables the application to share the specified file with another application. |
Redeemtokenforfileasync |
Another application uses this file by sharing tokens with a file. |
RemoveFile |
Revoke the existing shared token. |
The steps for using the Sharedstorageaccessmanager feature are broadly divided into the following three steps:
- The source app uses the AddFile method to get shared token strings for shared files
- Launch the recipient app and pass the token in a launchuriasync way
- Recipient app gets shared files by calling the Redeemtokenforfileasync method
You can see that using Sharedstorageaccessmanager to share a file is very convenient, but it is important to note that the use of Sharedstorageaccessmanager is still a certain limit:
- Shared tokens are valid only once, meaning that they are redeemtokenforfileasync by other apps.
- If the shared token has not been called Redeemtokenforfileasyncby another app, it will expire after 14 days
- Each app cannot share more than 1000 tokens, but when tokens are redeemed, removed, or expired by another app, they will not be counted to the number of tokens (1000) Redeem
Next, let's take a simple example to see how the Sharedstorageaccessmanager is used.
Example: We share an image file in one app to another app
First create the Audience app, page layout an image and a share button as follows:
Share front-end XAML:
1 <GridBackground="{ThemeResource Applicationpagebackgroundthemebrush}">2 <StackPanelHorizontalAlignment= "Center"VerticalAlignment= "Center">3 <ImageSource= "Images/img.jpg"/>4 <ButtonClick="{x:bind Sharefiletootherapp}"Content= "Share this image to another app"HorizontalAlignment= "Right"/>5 </StackPanel>6 </Grid>
Share the implementation of the button click Method:
1 Private Async voidSharefiletootherapp (Objectsender, RoutedEventArgs args)2 {3 varFile =awaitPackage.Current.InstalledLocation.GetFileAsync (@"images\img.jpg");4 5 //because the picture is being used in the UI, we're going to create another copy of the picture file to share.6 varLocalfolder =ApplicationData.Current.LocalFolder;7 varFilePath = $"{guid.newguid (). ToString ("N")}.jpg";8 varSamplefile =awaitLocalfolder.createfileasync (FilePath, creationcollisionoption.replaceexisting);9 awaitfile. Copyandreplaceasync (samplefile);Ten One //get tokens for the files you want to share A varSharingtoken =Sharedstorageaccessmanager.addfile (samplefile); - - //set the Uri of the App you want to share the varDriveto =NewUri ("aran.sharetargetsample:? sharedimgtoken="+sharingtoken); - varLaunch =awaitLauncher.launchuriasync (driveto); -}
Is it easy to get the code for the shared person to complete? Next we go to the receiver app, because we pass tokens to the recipient app through Launcher.launchuriasync, so we need to have the recipient app support the URI Initiation Protocol
First create a new project as the recipient, then double-click the open package.appxmanifest file, select the Declarations tab, add a declaration for the agreement, fill in the "Display name" and "name" of the agreement Declaration, for example:
It is important to note that the "name" is not used in uppercase letters.
This agreement is completed and saved and run under our program to check if the launch protocol is declared successful
We open the Computer "Control Panel-default program-Set the default program", if the declaration is successful, in the list of programs can find our set of Sharetargetsample program, click "Select this program default", you can see our launch protocol, as follows:
From the description information we can see that our URL is: aran.sharetargetsample, we open a file explorer, in the file path, type "Aran.sharetargetsample:" After the return, The system activates and launches our app via the URL protocol.
To complete the above operation is only able to launch our program through the URL activation, then how to activate the program to get the parameters passed to the outside? We need to override the Onactivated method in the recipient's App.cs app class to determine whether the app is launched by the URL protocol, and if so, get the parameters
The Onactivated method code is as follows:
1 protected Async Override voidOnActivated (Iactivatedeventargs args)2 {3 Base. OnActivated (args);4 //determine if the Launchuriasync mode starts5 if(args. Kind! = activationkind.protocol)return;6 varProtocolargs = args asProtocolactivatedeventargs;7 8 //get the file token from the URI9 if(Protocolargs = =NULL)return;Ten varQuerystrings =NewWwwformurldecoder (protocolArgs.Uri.Query); One varSharedimgtoken = Querystrings.getfirstvaluebyname ("Sharedimgtoken"); A - //read the file according to the token - if(string. IsNullOrEmpty (Sharedimgtoken))return; the varFile =awaitSharedstorageaccessmanager.redeemtokenforfileasync (sharedimgtoken); - - //Create a file locally to receive the files - varLocalfolder =ApplicationData.Current.LocalFolder; + varFilePath = $"{guid.newguid (). ToString ("N")}.jpg"; - varSamplefile =awaitLocalfolder.createfileasync (FilePath, creationcollisionoption.replaceexisting); + awaitfile. Copyandreplaceasync (samplefile); A at - //Get page reference - varroot = Window.Current.Content asFrame; - if(Root = =NULL) - { -Root =NewFrame (); inWindow.Current.Content =Root; - } to //navigate to the specified page and pass the file path +Root. Navigate (typeof(MainPage), Path.Combine (Localfolder.path, FilePath)); - //Make sure the current window is active the Window.Current.Activate (); *}
Because the program can be activated in a variety of ways, So in the above method we first want to determine whether the recipient app is activated by the type Activationkind.protocol, and then we will be based on the parameters in the URL to obtain the token value of the shared file and through the Sharedstorageaccessmanager.redeemtok Enforfileasync method to get shared files (here we ignore whether the app is already running and ignore jump to mainpage page is reasonable, the project can jump to other pages according to demand)
After we get the shared file, we save the file to our app root, then pass the file path to the page showing the shared file and jump to it.
The logic of the shared file Display page is simple, get the file path where the shared file is stored, and then show the file with the following code:
1 Public Sealed Partial classMainpage:page, INotifyPropertyChanged2 {3 PrivateImageSource _imguri;4 PublicImageSource Imguri5 {6 Get{return_imguri;}7 Set8 {9_imguri =value;Ten sendpropertychanged (); One } A } - - Public EventPropertyChangedEventHandler propertychanged; the Public voidSendpropertychanged ([Callermembername]stringPropertyName =NULL) - { - varHandler =propertychanged; -Handler?. Invoke ( This,NewPropertyChangedEventArgs (PropertyName)); + } - + A PublicMainPage () at { - This. InitializeComponent (); - } - - protected Override voidonnavigatedto (NavigationEventArgs e) - { in if(E.parameter! =NULL&&! (string. IsNullOrEmpty (E.parameter.tostring ()) && E.parameter is string)) - { toImguri =NewBitmapImage (NewUri (e.parameter.tostring (), Urikind.relativeorabsolute)); + } - Base. Onnavigatedto (e); the } *}
The foreground page XAML places an image element, binding the source of the image to the background Imguri property.
Final effect:
WIN10/UWP new features-sharedstorageaccessmanager shared files