Windows10 Dev - Communication avec les applications

La communication d'application à application signifie que votre application peut parler ou communiquer avec une autre application installée sur le même appareil. Il ne s'agit pas d'une nouvelle fonctionnalité de l'application Universal Windows Platform (UWP) et était également disponible dans Windows 8.1.

Dans Windows 10, des moyens nouveaux et améliorés sont introduits pour communiquer facilement entre les applications sur le même appareil. La communication entre deux applications peut se faire des manières suivantes -

  • Une application lance une autre application avec des données.
  • Les applications échangent simplement des données sans rien lancer.

Le principal avantage de la communication d'application à application est que vous pouvez diviser les applications en plus petits morceaux, qui peuvent être maintenus, mis à jour et consommés facilement.

Préparer votre application

Si vous suivez les étapes ci-dessous, d'autres applications peuvent lancer votre application.

  • Ajoutez une déclaration de protocole dans le manifeste du package d'application.

  • Double-cliquez sur le Package.appxmanifest fichier, qui est disponible dans l'Explorateur de solutions comme indiqué ci-dessous.

  • Aller au Declaration et écrivez le nom du protocole comme indiqué ci-dessous.

  • La prochaine étape consiste à ajouter le activation code, afin que l'application puisse répondre de manière appropriée lorsqu'elle est lancée par l'autre application.

  • Pour répondre aux activations de protocole, nous devons remplacer le OnActivatedméthode de la classe d'activation. Alors, ajoutez le code suivant dansApp.xaml.cs fichier.

protected override void OnActivated(IActivatedEventArgs args) {
 
   ProtocolActivatedEventArgs protocolArgs = args as ProtocolActivatedEventArgs;
	
   if (args != null){ 

      Frame rootFrame = Window.Current.Content as Frame;
	  
      // Do not repeat app initialization when the Window already has content, 
      // just ensure that the window is active
	  
      if (rootFrame == null){ 
		 
         // Create a Frame to act as the navigation context and navigate to the first page
         rootFrame = new Frame(); 
		 
         // Set the default language 
         rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];  
         rootFrame.NavigationFailed += OnNavigationFailed;
		 
         // Place the frame in the current Window 
         Window.Current.Content = rootFrame; 
      } 
		
      if (rootFrame.Content == null){
	  
         // When the navigation stack isn't restored, navigate to the  
         // first page, configuring the new page by passing required  
         // information as a navigation parameter 
		 
         rootFrame.Navigate(typeof(MainPage), null); 
      } 
		
      // Ensure the current window is active 
      Window.Current.Activate(); 
		
   } 
}
  • Pour lancer l'application, vous pouvez simplement utiliser le Launcher.LaunchUriAsync méthode, qui lancera l'application avec le protocole spécifié dans cette méthode.

await Windows.System.Launcher.LaunchUriAsync(new Uri("win10demo:?SomeData=123"));

Comprenons cela avec un exemple simple dans lequel nous avons deux applications UWP avec ProtocolHandlerDemo et FirstProtocolHandler.

Dans cet exemple, le ProtocolHandlerDemo l'application contient un bouton et en cliquant sur le bouton, elle ouvrira le FirstProtocolHandler application.

Le code XAML dans l'application ProtocolHandlerDemo, qui contient un bouton, est indiqué ci-dessous.

<Page 
   x:Class = "ProtocolHandlerDemo.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:ProtocolHandlerDemo" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">  
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <Button x:Name = "LaunchButton" Content = " Launch First Protocol App"
         FontSize = "24" HorizontalAlignment = "Center" 
         Click = "LaunchButton_Click"/> 
   </Grid> 
	
</Page>

Vous trouverez ci-dessous le code C #, dans lequel l'événement de clic sur le bouton est implémenté.

using System; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls;  

// The Blank Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  

namespace ProtocolHandlerDemo {

   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
   
   public sealed partial class MainPage : Page {
   
      public MainPage(){ 
         this.InitializeComponent(); 
      }
		
      private async void LaunchButton_Click(object sender, RoutedEventArgs e) {
         await Windows.System.Launcher.LaunchUriAsync(new 
            Uri("win10demo:?SomeData=123")); 
      }
		
   }
}

Voyons maintenant la FirstProtocolHandlertableau d'application. Ci-dessous, le code XAML dans lequel un bloc de texte est créé avec certaines propriétés.

<Page 
   x:Class = "FirstProtocolHandler.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:FirstProtocolHandler" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">  
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <TextBlock Text = "You have successfully launch First Protocol Application" 
         TextWrapping = "Wrap" Style = "{StaticResource SubtitleTextBlockStyle}"  
         Margin = "30,39,0,0" VerticalAlignment = "Top" HorizontalAlignment = "Left" 
         Height = "100" Width = "325"/> 
   </Grid> 
	
</Page>

L'implémentation C # du App.xaml.cs fichier dans lequel OnActicatedest remplacé est montré ci-dessous. Ajoutez le code suivant à l'intérieur de la classe App dans leApp.xaml.cs fichier.

protected override void OnActivated(IActivatedEventArgs args) { 
   ProtocolActivatedEventArgs protocolArgs = args as ProtocolActivatedEventArgs;
	
   if (args != null) {
      Frame rootFrame = Window.Current.Content as Frame;  
		
      // Do not repeat app initialization when the Window already has content, 
      // just ensure that the window is active 
		
      if (rootFrame == null) {

         // Create a Frame to act as the navigation context and navigate to 
            the first page 
         rootFrame = new Frame(); 
		 
         // Set the default language 
         rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];  
         rootFrame.NavigationFailed += OnNavigationFailed; 
		 
         // Place the frame in the current Window 
         Window.Current.Content = rootFrame; 
      }  
		
      if (rootFrame.Content == null) {
		
         // When the navigation stack isn't restored navigate to the 
         // first page, configuring the new page by passing required 
         // information as a navigation parameter 
		 
         rootFrame.Navigate(typeof(MainPage), null); 
      }
		
      // Ensure the current window is active 
      Window.Current.Activate(); 
   } 
}

Lorsque vous compilez et exécutez le ProtocolHandlerDemo application sur un émulateur, vous verrez la fenêtre suivante.

Maintenant, lorsque vous cliquez sur le bouton, cela ouvrira le FirstProtocolHandler application comme indiqué ci-dessous.