Windows Phone 8 Learning Note (4) app startup

Source: Internet
Author: User



Windows Phone 8 apps can be opened in other ways, in addition to being opened directly from the Start menu and the app list. The photo center, Music + video Center provides an extended support app to start from. In addition, we can launch the app through file associations, URI associations, and so on.



Quick navigation:
First, expand the music + video Center
Second, expand the photo center
Third, file association and SD card access
Iv. URI Association
V. Start my other apps and launch the built-in apps one, expand music + video Center 1) launch apps in music + video Center



Expand Music + video Center The first step is to ensure that the app can be launched from the Music + video Center, we need to manually modify the Windows Phone app manifest file, On the Wmappmanifest.xml file right-click, select Open Mode, open with an XML text editor, we need to set the app node under the Hubtype value of 1, the code is as follows:



[XML]


<app xmlns= "" hubtype= "1" productid= "{4887def4-a91a-465f-8eda-a3b07d8c12c2}" title= "Audio expansion example" Runtimetype= " Silverlight "version=" 1.0.0.0 "genre=" Apps.normal "author=" Phone av extension Author "description=" Sample Description " publisher= "Phone av extension" >......</App>
2) Update history, Latest listing list


After the app is integrated into the Music + video Center, we can update the history list of the music + video Center, the history is playing the tile, the latest listing, etc., and the following code describes how to update it.



[C #]


// Build MediaHistoryItem based on song (media item information)
        private MediaHistoryItem getMediaHistoryItem (Song song)
        {
            MediaHistoryItem mediaHistoryItem = new MediaHistoryItem ();
            // Thumbnail of current song album
            mediaHistoryItem.ImageStream = song.Album.GetThumbnail ();
            mediaHistoryItem.Source = string.Empty;
            // music name, will be displayed on the thumbnail
            mediaHistoryItem.Title = song.Name;
            mediaHistoryItem.PlayerContext.Add ("KeySring", song.Name);
            return mediaHistoryItem;
        }

        // Update the playing list in the history list
        private void updatePlaying (Song song)
        {
            MediaHistory.Instance.NowPlaying = getMediaHistoryItem (song);
        }

        // Update history list
        private void updateHistoryList (Song song)
        {
            MediaHistory.Instance.WriteRecentPlay (getMediaHistoryItem (song));
        }

        // Update the latest listing
        private void updateNewList (Song song)
        {
            MediaHistory.Instance.WriteAcquiredItem (getMediaHistoryItem (song));
        }


We can also customize other music, in addition to the update history and the latest listing of music in the Media Library. This way, music from non-media libraries can also be updated. But there may be some problems. The following code shows the music playing the installation folder and updates the playlist.



[C #]


// Read album thumbnails from the installation folder
StreamResourceInfo jpgStreamResourceInfo = Application.GetResourceStream (new Uri ("myImg.jpg", UriKind.Relative));

MediaHistoryItem mediaHistoryItem = new MediaHistoryItem ();
// Thumbnail of current song album
mediaHistoryItem.ImageStream = jpgStreamResourceInfo.Stream;
mediaHistoryItem.Source = string.Empty;
// music name, will be displayed on the thumbnail
mediaHistoryItem.Title = "My Music";
mediaHistoryItem.PlayerContext.Add ("KeySring", "My Music");
// Ready to play
mediaElement1.Source = new Uri ("1.mp3", UriKind.Relative);
mediaElement1.Play ();

// Update the music video center is playing, the non-media library music seems to restart the phone to see the effect, I do n’t know if it is a bug.
MediaHistory.Instance.NowPlaying = mediaHistoryItem;
3) Playback processing from the time of history and the latest market launch


When the user clicks on the corresponding item in the Music + video center, it will automatically launch our app, and this time we need to do some processing to determine which music to play. Our processing logic here only considers music that exists in the Media Library.



[C #]


protected override void OnNavigatedTo (System.Windows.Navigation.NavigationEventArgs e)
  {

      // When starting from Music Video Center, play the corresponding item.
      MediaLibrary library = new MediaLibrary ();
      Song _playingSong = null;
      if (NavigationContext.QueryString.ContainsKey ("KeySring"))
      {
          String songToPlay = NavigationContext.QueryString ["KeySring"];
          foreach (Song song in library.Songs)
          {
              if (songToPlay == song.Name)
              {
                  _playingSong = song;
                  break;
              }
          }
          if (_playingSong! = null)
              MediaPlayer.Play (_playingSong);

      }
      base.OnNavigatedTo (e);
  }
Second, expand the photo center


At some point, the user may want to launch a photo-processing-related app directly from the photo center, or to beautify the photos while they're browsing, or to upload the share to the web, to other apps, and at this point we'll need to extend the center of the photo, and our app can be launched right here. 1) Introduction of relevant extension points



1. Photo Center: After the extension, users can launch your app directly in the photos center. Such as:



2. Extended Share picker: You can launch the app from the share link and provide a shared photo of the user to another location, network, or email. Effects such as:



3. Extended photo Editing Picker: You can launch apps from the edit link and allow users to edit their photos, or if no extension is applied here, open the built-in photo editor, or the Select page pops up. Effects such as:



4. Extended Rich Media application: If the photo is saved or modified with the current app, the photo will show a special open link, rich media does not mean to edit the photo itself, but contains the text description of the picture, as well as for rich editing such as web interaction, such as microblogging applications. Effects such as:



5. Extended photo App Picker: This extension is only supported in WP7, and later versions are deprecated. Equivalent to editing in WP8 and rich editing. 2) Extended Photo Center



The extended photo Center needs to edit the manifest file, right-click on the Wmappmanfiest.xml file, select Open With, and select the XML text editor to open in the pop-up window. After the Tokens element, add the following code inside the Extensions element:



[XML]


<Extensions>
       <!-Extended Photo Center->
       <Extension ExtensionName = "Photos_Extra_Hub" ConsumerID = "{5B04B775-356B-4AA0-AAF8-6491FFEA5632}" TaskID = "_ default" />
     </ Extensions>
3) Extended Photo Viewer


The relevant extension points for the image viewer are described above, and we show you how to implement these extensions in code below. First, each extension point requires support for the manifest file, and we need to add the extensions entry in the same location. The code is as follows:



[XML]


<Extensions>
       <!-Extended Photo Center->
       <Extension ExtensionName = "Photos_Extra_Hub" ConsumerID = "{5B04B775-356B-4AA0-AAF8-6491FFEA5632}" TaskID = "_ default" />
       <!-Extended shared picker->
       <Extension ExtensionName = "Photos_Extra_Share" ConsumerID = "{5B04B775-356B-4AA0-AAF8-6491FFEA5632}" TaskID = "_ default" />
       <!-Extending Rich Media Applications->
       <Extension ExtensionName = "Photos_Rich_Media_Edit" ConsumerID = "{5B04B775-356B-4AA0-AAF8-6491FFEA5632}" TaskID = "_ default" />
       <!-Extended photo editing picker->
       <Extension ExtensionName = "Photos_Extra_Image_Editor" ConsumerID = "{5B04B775-356B-4AA0-AAF8-6491FFEA5632}" TaskID = "_ default" />
     </ Extensions>


After the manifest file supports these extensions, when the user launches the app by extension, the photo center launches the mainpage.xaml of our app by default, and tells us which image to do with the URI parameter. Here we implement the processing parameter information by parsing the URI parameter in MainPage.xaml. If your app has dedicated page handling, you need to implement URI mapping, see here for URI mapping.
[XAML]


<Grid x: Name = "ContentPanel" Grid.Row = "1" Margin = "12,0,12,0">
             <Image x: Name = "image1" HorizontalAlignment = "Left" Height = "480" Margin = "10,80,0,0" VerticalAlignment = "Top" Width = "436" />
             <TextBlock HorizontalAlignment = "Left" Margin = "10,36,0,0" TextWrapping = "Wrap" Text = "Picture source method:" VerticalAlignment = "Top" />
             <Button Content = "Save" HorizontalAlignment = "Left" Margin = "315,609,0,0" VerticalAlignment = "Top" Click = "Button_Click_1" />
             <TextBlock x: Name = "textBlock1" Foreground = "Yellow" HorizontalAlignment = "Left" Margin = "170,36,0,0" Grid.Row = "1" TextWrapping = "Wrap" Text = "Unknown" VerticalAlignment = " Top "/>
         </ Grid>


[C #]


Picture selectedPicture;
        protected override void OnNavigatedTo (System.Windows.Navigation.NavigationEventArgs e)
        {
            IDictionary <string, string> queryStrings = this.NavigationContext.QueryString;

            if (! queryStrings.ContainsKey ("Action"))
            {
                textBlock1.Text = "No Source";

            }
            else
            {
                string action = queryStrings ["Action"];
                switch (action)
                {
                    case "ShareContent": textBlock1.Text = "Share picker";
                        break;
                    case "RichMediaEdit": textBlock1.Text = "Rich Media Application";
                        break;
                    case "EditPhotoContent": textBlock1.Text = "Photo edit picker";
                        break;
                }

                MediaLibrary library = new MediaLibrary ();
                
                if (queryStrings.ContainsKey ("FileId")) selectedPicture = library.GetPictureFromToken (queryStrings ["FileId"]);
                else if (queryStrings.ContainsKey ("token")) selectedPicture = library.GetPictureFromToken (queryStrings ["token"]);
                else return;
                BitmapImage bitmapFromPhoto = new BitmapImage ();
                bitmapFromPhoto.SetSource (selectedPicture.GetImage ());
                image1.Source = bitmapFromPhoto;
            }
            base.OnNavigatedTo (e);
        }

        //save Picture
        private void Button_Click_1 (object sender, RoutedEventArgs e)
        {
            MediaLibrary library = new MediaLibrary ();
            library.SavePicture (selectedPicture.Name, selectedPicture.GetImage ());
        }
4) Summary of extension methods


Above we found that the URI launched by the photo Viewer has an action parameter, and a parameter is either Fileid or token. The following list summarizes:



Extension points
Extension names in the manifest file
URI Start Association Address
Supported platforms



Photo Center
Photos_extra_hub
Wp7\wp8



Share Picker
Photos_extra_share
/mainpage.xaml? ACTION=SHARECONTENT&FILEID=[GUID]
Wp7\wp8



Rich Media applications
Photos_rich_media_edit
/mainpage.xaml? ACTION=RICHMEDIAEDIT&TOKEN=[GUID]
WP8



Photo Editing picker
Photos_extra_image_editor
/mainpage.xaml? ACTION=EDITPHOTOCONTENT&FILEID=[GUID]
WP8



Photo App Picker
Photos_extra_viewer
/MAINPAGE.XAML?TOKEN=[GUID]
WP7 Third, file association and SD card access



File associations, as the name implies, are similar to registering a default startup program in Windows systems. We can also register our app as the default launcher for certain suffix files. As we have said before, an app can access the storage location of only the installation folder, local folder, Media Library three locations, but we can register the file association, as long as the associated files, even in other locations we may also access, this file may be from the SD card, may also be from other applications. 1. How to register a file association



To work with a specific file type, register the file association in the app manifest file. Again, we need to open the Wmappmanifest.xml file in the right-click mode and choose the XML Text editor. The Extensions node must be added after the Tokens node, in Extensions we define the associated file suffix name, the large small and medium-sized logo that already has the file. The code is as follows:



[XML]


<Extensions>
       <FileTypeAssociation Name = "File association description information" TaskID = "_ default" NavUriFragment = "fileToken =% s">
         <Logos>
           <!-Define the logo for the associated file type, large, medium and small->
           <Logo Size = "small" IsRelative = "true"> medium33x33.png </ Logo>
           <Logo Size = "medium" IsRelative = "true"> medium69x69.png </ Logo>
           <Logo Size = "large" IsRelative = "true"> large176x176.png </ Logo>
         </ Logos>
         <!-Define the associated file extension->
         <SupportedFileTypes>
           <FileType ContentType = "application / myfile1">. Myfile3 </ FileType>
           <FileType ContentType = "application / myfile2">. Myfile2 </ FileType>
         </ SupportedFileTypes>
       </ FileTypeAssociation>
     </ Extensions>
2. Listen for file startup


When a user opens your associated file type through an SD card or other app, the system launches your app and sends a URI in the following format:
/FILETYPEASSOCIATION?FILETOKEN=[GUID]



But we find that this URI is not directly related to a page of our application, so now we need to define a URI map to handle this particular URL. Convert it to a standard URI to guide the MainPage.xaml. Registering URI Conversions:



First, we need to define a urimapper that implements the logic of URI translation. To create a new class file AssociationUriMapper.cs, enter the following code:



[C #]


public class AssociationUriMapper: UriMapperBase
  {

      public override Uri MapUri (Uri uri)
      {
          string tempUri = System.Net.HttpUtility.UrlDecode (uri.ToString ());

          // Verify whether Uri is caused by file association
          if (tempUri.StartsWith ("/ FileTypeAssociation? fileToken ="))
          {
              string fileToke = tempUri.Substring (31);
              // Organize it into a canonical URL and post it to MainPage.xaml
              return new Uri ("/ MainPage.xaml? fileToke =" + fileToke, UriKind.Relative);
          }
          return uri;
      }
  }


Then we need to register our URI conversion class in App.cs's Initializephoneapplication method. Add methods such as:






Below, we are going to recognize the heard file as a text file and display it with the following code:



[C #]


protected async override void OnNavigatedTo (NavigationEventArgs e)
{
     // Get URI parameters
     IDictionary <string, string> queryStrings = NavigationContext.QueryString;

     if (queryStrings.ContainsKey ("fileToke"))
     {
         var fileToke = queryStrings ["fileToke"];
         // Get the file name
         var fileName = SharedStorageAccessManager.GetSharedFileName (fileToke);
         // local folder
         var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
         // Copy the file to a file with the same name in a local folder
         var file = await SharedStorageAccessManager.CopySharedFileAsync (localFolder, fileName, NameCollisionOption.ReplaceExisting, fileToke);
         var stream = await file.OpenAsync (FileAccessMode.Read);

         StreamReader s = new StreamReader (stream.AsStream (), System.Text.Encoding.Unicode);
         var fileText = s.ReadToEnd ();
         MessageBox.Show ("File name:" + fileName + "\ nContent:" + fileText);
     }
     base.OnNavigatedTo (e);
}
3. Start the associated file


When a third-party application wants to open the associated file itself and does not want to implement the logic of parsing the file itself, it can automatically launch our app to open it.



[C #]


// Initialize file list
private async void filesInit ()
{
     // local folder
     var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
     var files = await localFolder.GetFilesAsync ();
     listboxFiles.ItemsSource = files.Where (x => x.Name.EndsWith (". myfile1") || x.Name.EndsWith (". myfile2"));
}

// Open the selected file and jump to the application of the associated file
private async void Button_Click_2 (object sender, RoutedEventArgs e)
{
     StorageFile file = listboxFiles.SelectedItem as StorageFile;
     if (file == null) return;
     // Launch the application associated with the specified file to open the file
     Windows.System.Launcher.LaunchFileAsync (file);
}


Show the effect of the run through the diagram:
4. Accessing the SD card



If you have our associated file type in the SD card, we can also actively traverse it to access it. The code that implements accessing the SD card and reading the file text class size is as follows:



[XAML]


<!-ContentPanel-place additional content here->
        <Grid x: Name = "ContentPanel" Grid.Row = "1" Margin = "12,0,12,0">
            <ListBox x: Name = "listboxFiles" Margin = "10,92,135,288">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text = "{Binding Name}" />
                    </ DataTemplate>
                </ListBox.ItemTemplate>
                <ListBox.ItemContainerStyle>
                    <Style TargetType = "ListBoxItem">
                        <Setter Property = "Margin" Value = "5" />
                        <Setter Property = "Background" Value = "Blue" />
                    </ Style>
                </ListBox.ItemContainerStyle>
            </ ListBox>
            <TextBlock Text = "List of SD card readable files:" HorizontalAlignment = "Left" Margin = "10,53,0,0" TextWrapping = "Wrap" VerticalAlignment = "Top">
            </ TextBlock>
            <Button Content = "Open selection" HorizontalAlignment = "Left" Margin = "315,465,0,0" VerticalAlignment = "Top" Click = "Button_Click_1" />
        </ Grid>


[C #]


protected override void OnNavigatedTo (NavigationEventArgs e)
        {
            filesInit ();
            base.OnNavigatedTo (e);
        }

        // Initialization file list, contains only identifiable files
        private async void filesInit ()
        {
            // Get the SD card set inserted into the mobile phone, generally at most one SD card.
            var externalStorageDevices = await ExternalStorage.GetExternalStorageDevicesAsync ();
            // Get the first SD card in the collection
            ExternalStorageDevice sdCard = externalStorageDevices.FirstOrDefault ();
            if (sdCard == null)
            {
                MessageBox.Show ("No SD card was found, please check if the SD card is inserted properly.");
                return;
            }
            // Get all files in the root directory
            var files = await sdCard.RootFolder.GetFilesAsync ();
            listboxFiles.ItemsSource = files.Where (x => x.Name.EndsWith (". myfile1") || x.Name.EndsWith (". myfile2"));
        }

        // Open the selected file in the file list
        private async void Button_Click_1 (object sender, RoutedEventArgs e)
        {

            ExternalStorageFile file = listboxFiles.SelectedItem as ExternalStorageFile;
            if (file == null) return;
            // Read the file
            var stream = await file.OpenForReadAsync ();

            StreamReader s = new StreamReader (stream, System.Text.Encoding.Unicode);
            var fileText = s.ReadToEnd ();
            MessageBox.Show ("File name:" + file.Name + "\ nContent:" + fileText);

        }
Iv. URI Association


Imagine this scenario where we want to take advantage of App B's functionality in application A. We don't want to do the same thing ourselves because B is quite mature, and there's no need to do it again. For example: We click on a phone number, we want to directly open the dial-up software to start dialing, click an email, directly open the email app to write a message, click on a video name, you can open the video player to play the video. At this point, you need to take advantage of the URI-associated functionality. 1. Registering URI Associations



URI associated with the registration also need to edit the manifest file, right-click on the Wmappmanfiest.xml file, select Open Mode, in the Pop-up window select the XML text editor to open. After the Tokens element, add the following code inside the Extensions element:



[XML]


<Extensions>
       <!-Register associated URI, Name part is your specific URI prefix->
       <Protocol Name = "testuri" NavUriFragment = "encodedLaunchUri =% s" TaskID = "_ default" />
     </ Extensions>


Once registered, third-party apps can navigate to our app with the following URI:



testuri:[parameter section] 2. Listen for URIs



Once the URI Association has been registered, the other applications in the system all URI requests prefixed with Testuri are captured by our app, and we need to define a URI transform to get MainPage.xaml.



[C #]


class AssociationUriMapper: UriMapperBase
     {
         private string tempUri;

         public override Uri MapUri (Uri uri)
         {
             tempUri = System.Net.HttpUtility.UrlDecode (uri.ToString ());

             // Verify that Uri is a registered association
             if (tempUri.StartsWith ("/ Protocol? encodedLaunchUri = testuri:"))
             {
                 string uriMsg = tempUri.Substring (35);
                 return new Uri ("/ MainPage.xaml? Msg =" + uriMsg, UriKind.Relative);
             }
             return uri;
         }
     }


We also need to register URI conversions in the Initializephoneapplication method



[C #]


/ * In App InitializePhoneApplication method, we need to register URI conversion * /

        // don't add any other code to this method
        private void InitializePhoneApplication ()
        {
            if (phoneApplicationInitialized)
                return;

            // Create the framework without first setting it to RootVisual; this allows the initial
            // The screen remains active until ready to render the application.
            RootFrame = new PhoneApplicationFrame ();
            RootFrame.Navigated + = CompleteInitializePhoneApplication;

            // The part of the code we inserted! !! !!
            // Register our URI conversion
            RootFrame.UriMapper = new AssociationUriMapper ();

            // Handle navigation failure
            RootFrame.NavigationFailed + = RootFrame_NavigationFailed;

            // Process the reset request to clear BackStack in the next navigation,
            RootFrame.Navigated + = CheckForResetNavigation;

            // make sure we don't initialize again
            phoneApplicationInitialized = true;
        }


To process the URI Association request in MainPage.xaml, the code is as follows:



[C #]


protected override void OnNavigatedTo (NavigationEventArgs e)
         {
             IDictionary <string, string> queryStrings = NavigationContext.QueryString;
             if (queryStrings.ContainsKey ("Msg")) MessageBox.Show ("Caller information from URI association: \ n" + queryStrings ["Msg"]);
             base.OnNavigatedTo (e);
         }
3. Launch URI


How does the caller start the associated URI? The code is as follows:



[C #]


 private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            var c = await Windows.System.Launcher.LaunchUriAsync(new System.Uri("testuri:"+textbox1.Text));
        }


Finally, let's look at the demo effect:
V. Start my other apps and launch the built-in apps 1. Start my other Apps



My app is a Publisher ID app, we can set this ID in the manifest file, and the following code shows the second app that launches the list of apps I published.



[C #]


// Launch other apps I publish
         private void Button_Click_1 (object sender, RoutedEventArgs e)
         {
             // Query other apps on this machine that have the same issuer ID as the current app
             IEnumerable <Package> apps = Windows.Phone.Management.Deployment.InstallationManager.FindPackagesForCurrentPublisher ();
             // Launch the second application
             apps.Skip (1) .First (). Launch (string.Empty);
         }
2. Launch the built-in app


Built-in applications refer to the application of the WP8 phone system itself, and we can start them in a fixed way. The following code demonstrates how to use the.



[C #]


// Launch the built-in application
        private void Button_Click_2 (object sender, RoutedEventArgs e)
        {
            // Open IE to access Baidu
            //Windows.System.Launcher.LaunchUriAsync(new Uri ("http://www.baidu.com"));

            // Open the built-in mailbox to send mail
            //Windows.System.Launcher.LaunchUriAsync(new Uri ("mailto: [email protected]"));

            // Call mobile
            //Windows.System.Launcher.LaunchUriAsync(new Uri ("tel: 13900000000"));

            // Enable Wi-Fi settings
            //Windows.System.Launcher.LaunchUriAsync(new Uri ("ms-settings-wifi:"));

            //others
            // ms-settings-accounts: Launch the account settings app.
            // ms-settings-airplanemode: Launch the flight mode settings application.
            // ms-settings-bluetooth: Launch the Bluetooth settings app.
            // ms-settings-cellular: Launch the mobile network settings application.
            // ms-settings-emailandaccounts: Launch the email and account settings app.
            // ms-settings-location: Launch the location settings application.
            // ms-settings-lock: Launch the lock screen settings application.
            // ms-settings-wifi: Launch the Wi-Fi settings app.


            // Launch the Windows Phone store and display the details page for a specific app.
            //Windows.System.Launcher.LaunchUriAsync(new Uri ("zune: navigate? Appid = fdf05477-814e-41d4-86cd-25d5a50ab2d8"));
            // Launch the store and display the viewing page of the calling app.
            //Windows.System.Launcher.LaunchUriAsync(new Uri ("zune: reviewapp"));
            // Launch the store and display the view page for a specific app
            //Windows.System.Launcher.LaunchUriAsync(new Uri ("zune: reviewapp? Appid = appfdf05477-814e-41d4-86cd-25d5a50ab2d8"));
            // Launch the store and search
            //Windows.System.Launcher.LaunchUriAsync(new Uri ("zune: search? Keyword = keyword & publisher = publisher name & contenttype = app"));
        } 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.