Google WindowsPhone 8 Custom URI Scheme:Launching other own apps from your app (C#-XAML) | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Wednesday 4 June 2014

WindowsPhone 8 Custom URI Scheme:Launching other own apps from your app (C#-XAML)

Introduction:

It is very easy to launch another app with your app with help of "Custom URI Scheme" concept.So it is way of promoting one app with other apps.However this post is explained about 
1)How to make custom uri scheme.
2)How to communication other own installed apps with your app.
3)How to send files between two apps

Building the Sample:

This sample is targeted on windowsphone 8.0 OS.

Description:

Ok,lets understand the sample

1)How to launch other apps from current app with custom URI association:

In this sample i have three apps
1)cFirstApp 2)cSecondApp 3)CustomURISchemeWP8
Here my main app is "CustomURISchemeWP8",when tapping launch button remaining two apps will be launched like below.And if only one app installed on device,then it will be directly redirect to corresponding launched app.  launching other apps














Note:When the user launches a file or URI from an app, what happens next depends on which apps are installed on the phone(i,e cFirstApp&cSecondApp) . If no apps on the phone can handle that particular file or URI association, the user will be given the option to get one that does like below.
To do above functionality we need to have following steps.
Step1:
 To work with URI association ,we must need to specify the corresponding URI scheme name in the app manifest file,i.e WMAppManifest.xml
To do ,in our sample we are launching two other apps i.e 1)cFirstApp,2)cSecondApp
so in these two apps we have to edit WMAppManifest.xml file like this way
XML
 <Extensions <Protocol Name="mycustomlaunch-otherapps" NavUriFragment="encodedLaunchUri=%s" TaskID="_default" /> 
 </Extensions>
In above code there protocol name is "mycustomlaunch-otherapps" .it is my custom uri scheme,so you may change it with your needs,and this name can be any combination of letters and numbers(2-39 chars),lowercased letters, periods ('.'), or hyphens ('-').
Step2:
Next we need to add Uri Mapper class for two projects (cFirstapp & cSecondApp)to handle URI association.Which is useful for mapping custom uri scheme named apps with current app.
C#
public class UriMapper : UriMapperBase 
    { 
        private string tempUri; 
 
        public override Uri MapUri(Uri uri) 
        { 
            // Map everything to the main page. 
            return new Uri("/MainPage.xaml", UriKind.Relative); 
        } 
    }
Step3: 

Now we are done almost,but finally we need to write a small single line code in App.xaml.cs file of two projects (both cFirstApp & cSecondApp)
 i.e,RootFrame.UriMapper = new UriSchemeMapper();
C#
 private void InitializePhoneApplication() 
        { 
            if (phoneApplicationInitialized) 
                return; 
 
            // Create the frame but don't set it as RootVisual yet; this allows the splash 
            // screen to remain active until the application is ready to render. 
            RootFrame = new PhoneApplicationFrame(); 
            RootFrame.Navigated += CompleteInitializePhoneApplication; 
            RootFrame.UriMapper = new UriSchemeMapper(); 
            // Handle navigation failures 
            RootFrame.NavigationFailed += RootFrame_NavigationFailed; 
 
            // Handle reset requests for clearing the backstack 
            RootFrame.Navigated += CheckForResetNavigation; 
 
            // Ensure we don't initialize again 
            phoneApplicationInitialized = true; 
        }
Step4:
 Finally its time to launch other apps using our own custom uri schem name like this way 
C#
Windows.System.Launcher.LaunchUriAsync(new Uri("mycustomlaunch-otherapps:"));
 Note: Here make sure your custom uri scheme name is followed by colon(:).And please read about LaunchUriAsync.

2)How to send file other apps from current app with custom file association:

In this sample i tried to share entered text file content between two apps cFirstApp & cSecondApp like this way 
Sharing TextFile to cSecondApp from cFirstApp.










Sharing TextFile to cFirstApp from cSecondApp.
Step1:
 And it is very similar functionality as we are discussed earlier in above.However to work with FileTypeAssociation,same we need extra to registere in WMAppManifest file as same like we done above for URI association.
C#
 <Extensions> 
       
        <Logos> 
           <Logo Size="small" IsRelative="true">Assets/sdk-small-33x33.png</Logo> 
           <Logo Size="medium" IsRelative="true">Assets/sdk-medium-69x69.png</Logo> 
           <Logo Size="large" IsRelative="true">Assets/sdk-large-176x176.png</Logo> 
         </Logos> 
 
        <FileTypeAssociation Name="TextFile" TaskID="_default" NavUriFragment="fileToken=%s"> 
        <SupportedFileTypes> 
          <FileType>.myextension1</FileType>//cFirstApp 
         <FileType>.myextension2</FileType>//cSecondApp 
        </SupportedFileTypes> 
      </FileTypeAssociation> 
      
    </Extensions>
 Here Lists all logos for a file association. This is optional when no logos are specified.
Step2: 
Next we need to Association Uri Mapper class to project
C#
 class UriSchemeMapper : UriMapperBase 
    { 
        private string tempUri; 
 
        public override Uri MapUri(Uri uri) 
        { 
            tempUri = uri.ToString(); 
 
            // File association launch 
            if (tempUri.Contains("/FileTypeAssociation")) 
            { 
                // Get the file ID (after "fileToken="). 
                int fileIDIndex = tempUri.IndexOf("fileToken=") + 10; 
                string fileID = tempUri.Substring(fileIDIndex); 
 
                // Get the file name. 
                string incomingFileName = 
                    SharedStorageAccessManager.GetSharedFileName(fileID); 
 
                // Get the file extension. 
                int extensionIndex = incomingFileName.LastIndexOf('.') + 1; 
                string incomingFileType = 
                    incomingFileName.Substring(extensionIndex).ToLower(); 
 
                // Map the .myextension appropriate pages. 
                switch (incomingFileType) 
                { 
                    case "myextension1": 
                        return new Uri("/MainPage.xaml?fileToken=" + fileID, UriKind.Relative); 
                    default: 
                        return new Uri("/MainPage.xaml", UriKind.Relative); 
                } 
            } 
 
            return new Uri("/MainPage.xaml", UriKind.Relative); 
            //tempUri = System.Net.HttpUtility.UrlDecode(uri.ToString()); 
 
        } 
    }
 Step3: 
Now its time to send file to other app like this way
C#
private async void submitbtn_Click(object sender, RoutedEventArgs e) 
        { 
            // Access local storage. 
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; 
 
            // Save the file in local storage 
            StorageFile file = await local.CreateFileAsync("txtfile.myextension1", CreationCollisionOption.ReplaceExisting); 
            if (file != null) 
            { 
                string userContent = ReceiveChatTxt.Text; 
                if (!String.IsNullOrEmpty(userContent)) 
                { 
                    using (StorageStreamTransaction strmtransaction = await file.OpenTransactedWriteAsync()) 
                    { 
                        using (DataWriter dataWriter = new DataWriter(strmtransaction.Stream)) 
                        { 
                            dataWriter.WriteString(userContent); 
                            strmtransaction.Stream.Size = await dataWriter.StoreAsync(); // reset stream size to override the file 
                            await strmtransaction.CommitAsync(); 
                        } 
                    } 
                    // Access the text file. 
                    StorageFile txtfile = await local.GetFileAsync("txtfile.myextension1"); 
 
                    // Launch the bug text file. 
                    Windows.System.Launcher.LaunchFileAsync(txtfile); 
                } 
                else 
                { 
                    MessageBox.Show("The text file is should not be empty."); 
                } 
            } 
        }
Step4: 
And finally recieve textfile at launched app like this way
C#
protected async override void OnNavigatedTo(NavigationEventArgs e) 
        { 
            base.OnNavigatedTo(e); 
 
            // Get a dictionary of URI parameters and values. 
            IDictionary<stringstring> queryStrings = this.NavigationContext.QueryString; 
 
            // Have we been launched to handle a file association? 
            if (queryStrings.ContainsKey("fileToken")) 
            { 
                // Yes we have - get the filetoken 
                string fileToken = queryStrings["fileToken"]; 
                // Copy the file from shared storage 
                string filename = SharedStorageAccessManager.GetSharedFileName(fileToken); 
                IStorageFile TxtFile = await SharedStorageAccessManager.CopySharedFileAsync( 
                    ApplicationData.Current.LocalFolder,    // Store in the local folder 
                    filename,                               // keep the same filename 
                    NameCollisionOption.ReplaceExisting,    // Replace any existing file of the same name 
                    fileToken); 
 
                // For this demo, just write the contents of the file to the screen 
                using (IRandomAccessStream readStream = await TxtFile.OpenAsync(FileAccessMode.Read)) 
                { 
                    using (DataReader dataReader = new DataReader(readStream)) 
                    { 
                        UInt64 size = readStream.Size; 
                        if (size <= UInt32.MaxValue) 
                        { 
                            UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size); 
                            string fileContent = dataReader.ReadString(numBytesLoaded); 
                            ReceiveChatTxt.Text = fileContent; 
                            submitbtn.Content = "Re-Submit"; 
                        } 
                        else 
                        { 
                            ReceiveChatTxt.Text = "File " + TxtFile.Name + " Files larger than 4GB ."; 
                        } 
                    } 
                } 
            } 
            else 
            { 
                ReceiveChatTxt.Text = "There is no text recieved from another app ."; 
                submitbtn.Visibility = Visibility.Collapsed; 
            } 
        } 

Source file at: CustomURISchemeSample
Note: Please share your thoughts,what you think about this post,Is this post really helpful for you?otherwise it would be very happy ,if you have any thoughts for to implement this requirement in any another way?I always welcome if you drop comments on this post and it would be impressive..


Follow me always at  

Have a nice day by  :)

8 comments:

  1. U superb ....Great work you done :)

    ReplyDelete
  2. Hi Dear,

    I have installed Visual Studio 2013 Update 2 and also installed SDK 8.0 as well as 8.1 in Windows 8.0 pro and
    64 bit os.
    But when i run the Windows app using Emulator 8.0 or Emulator 8.1 , it doesn't work. It give the following error :

    "Deploy Error 0x80131500 error code"

    Can you please help me to make it in running mode?

    Its very very urgent.

    Regard,
    Rohin Sharma

    ReplyDelete
    Replies
    1. Hi Rohin,

      Have you checked your processor must be support Hyper-v and Second Level Address Translation (SLAT).And have you tested with your actual device?

      Delete
  3. thanks for this great blog .
    for iphone apps you can check my6 link below .
    we have great experience to making facebook apps



    Custom IPhone Apps | IPhone Apps Developer

    ReplyDelete
  4. Hello Subbu

    Can you please let me know? How can append the URI scheme from HTML (JAVA Script) so that application can be opened from Email? And is this supported to WP 7.5 devices?

    Please help!

    Thanks!
    Ramesh

    ReplyDelete
  5. Thank you for the info. It sounds pretty user friendly. I guess I’ll pick one up for fun. thank u.

    Customized Phone Cases


    ReplyDelete

Search Engine Submission - AddMe