Windows10-development-services

提供:Dev Guides
移動先:案内検索

Windows 10開発-サービス

この章では、UWPアプリが他のユニバーサルWindowsプラットフォーム(UWP)アプリケーションにサービスを提供または提供する方法について学習します。 実際、この章は Background execution の章の拡張であり、特別な場合です。

  • Windows 10では、アプリサービスは、アプリが他のアプリにサービスを提供する方法またはメカニズムです。
  • アプリサービスはバックグラウンドタスクの形式で機能します。
  • フォアグラウンドアプリは、別のアプリのアプリサービスを呼び出して、バックグラウンドでタスクを実行できます。

APPサービス

アプリサービスはWebサービスに似ていますが、アプリサービスはWindows 10デバイスで使用されます。

ユニバーサルWindowsプラットフォーム(UWP)アプリケーションは、さまざまな方法で別のUWPアプリケーションと対話できます-

  • LaunchUriAsyncを使用したURIの関連付け
  • LaunchFileAsyncを使用したファイルの関連付け
  • LaunchUriForResultsAsyncを使用した結果の起動
  • アプリサービス

最初の3つの方法は、両方のアプリケーションがフォアグラウンドである場合に使用されますが、Appサービスは*バックグラウンドタスク*で使用され、その場合、クライアントアプリケーションはフォアグラウンドにあり、Appサービスを使用できる必要があります。

アプリサービスは、非ビジュアルサービスが提供されるアプリケーションで非常に有益です。 フォアグラウンドアプリが画像を取得し、それらのバイトをアプリサービスに送信してバーコードを識別するバーコードスキャナー。

これらすべての概念を理解するために、Microsoft Visual Studio 2015で AppServiceProvider という名前の新しいUWPプロジェクトを作成しましょう。

*Package.appmenifest* ファイルに、次の情報を追加します。

APPサービス

フォアグラウンドアプリケーションによって呼び出すことができるアプリサービスを作成するには、アプリサービスがバックグラウンドタスクとして実装されているため、新しい* Windowsランタイム*コンポーネントプロジェクトを MyAppService という名前でソリューションに追加します。

*AppServiceProvider* プロジェクトに *MyAppService* プロジェクトへの参照を追加します。
*MyAppService* プロジェクトから *class1.cs* ファイルを削除し、インベントリ名を持つ新しいクラスを追加します。これにより、 *IBackgrounTask* インターフェイスが実装されます。
*IBackgrounTask* インターフェースには、バックグラウンドタスク用に実装する必要がある*「Run」*メソッドが1つしかありません。
public sealed class Inventory : IBackgroundTask {
   public void Run(IBackgroundTaskInstance taskInstance) {

   }
}

バックグラウンドタスクが作成されると、* Run()メソッド*が呼び出され、Runメソッドが完了すると、バックグラウンドタスクが終了します。 バックグラウンドタスクにとどまり、リクエストを処理するために、コードは延期されます。

アプリサービスコードは* OnRequestedReceived()*にあります。 この例では、インベントリアイテムのインデックスがサービスに渡され、指定されたインベントリアイテムの名前と価格が取得されます。

private async void OnRequestReceived(AppServiceConnection sender,
   AppServiceRequestReceivedEventArgs args) {
     //Get a deferral because we use an awaitable API below to respond to the message
}

以下に、C#でのInventoryクラスの完全な実装を示します。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Windows.ApplicationModel.AppService;
using Windows.ApplicationModel.Background;
using Windows.Foundation.Collections;

namespace MyAppService{
   public sealed class Inventory : IBackgroundTask {

      private BackgroundTaskDeferral backgroundTaskDeferral;
      private AppServiceConnection appServiceconnection;

      private String[] inventoryItems = new string[] { "Robot vacuum", "Chair" };
      private double[] inventoryPrices = new double[] { 129.99, 88.99 };

      public void Run(IBackgroundTaskInstance taskInstance) {
         this.backgroundTaskDeferral = taskInstance.GetDeferral();
         taskInstance.Canceled += OnTaskCanceled;
         var details = taskInstance.TriggerDetails as AppServiceTriggerDetails;

         appServiceconnection = details.AppServiceConnection;
         appServiceconnection.RequestReceived += OnRequestReceived;
      }

      private async void OnRequestReceived(AppServiceConnection sender,
         AppServiceRequestReceivedEventArgs args) {

            var messageDeferral = args.GetDeferral();
            ValueSet message = args.Request.Message;
            ValueSet returnData = new ValueSet();

            string command = message["Command"] as string;
            int? inventoryIndex = message["ID"] as int?;
            if (inventoryIndex.HasValue &&

            inventoryIndex.Value >= 0 &&
            inventoryIndex.Value < inventoryItems.GetLength(0)) {

               switch (command) {

                  case "Price": {
                     returnData.Add("Result", inventoryPrices[inventoryIndex.Value]);
                     returnData.Add("Status", "OK");
                     break;
                  }

                  case "Item": {
                     returnData.Add("Result", inventoryItems[inventoryIndex.Value]);
                     returnData.Add("Status", "OK");
                     break;
                  }

                  default: {
                     returnData.Add("Status", "Fail: unknown command");
                     break;
                  }
               } else {
                  returnData.Add("Status", "Fail: Index out of range");
               }
            }
            await args.Request.SendResponseAsync(returnData);
            messageDeferral.Complete();
      }

      private void OnTaskCanceled(IBackgroundTaskInstance sender,
         BackgroundTaskCancellationReason reason){
            if (this.backgroundTaskDeferral != null) {
              //Complete the service deferral.
               this.backgroundTaskDeferral.Complete();
            }
      }
   }
}

新しい空のUWPプロジェクト ClientApp を追加してクライアントアプリを作成し、XAMLファイルに次のように1つのボタン、1つのテキストボックス、2つのテキストブロックを追加します。

<Page
   x:Class = "ClientApp.MainPage"
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local = "using:ClientApp"
   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 HorizontalAlignment = "Left" Text = "Enter Item No."
         Margin = "52,40,0,0" TextWrapping = "Wrap"
         VerticalAlignment = "Top" Height = "32" Width = "268"/>

      <Button x:Name = "button" Content = "Get Info" HorizontalAlignment = "Left"
         Margin = "255,96,0,0" VerticalAlignment = "Top" Click = "button_Click"/>

      <TextBox x:Name = "textBox" HorizontalAlignment = "Left" Margin = "52,96,0,0"
         TextWrapping = "Wrap" VerticalAlignment = "Top" Width = "168"/>

      <TextBlock x:Name = "textBlock" HorizontalAlignment = "Left"
         Margin = "52,190,0,0" TextWrapping = "Wrap"
         VerticalAlignment = "Top" Height = "32" Width = "268"/>
   </Grid>

</Page>

以下に、Appサービスが要求されるボタンクリックイベントの実装を示します。

using System;

using Windows.ApplicationModel.AppService;
using Windows.Foundation.Collections;

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 ClientApp {

  ///<summary>
     ///An empty page that can be used on its own or navigated to within a Frame.
  ///</summary>

   public sealed partial class MainPage : Page {

      private AppServiceConnection inventoryService;

      public MainPage() {
         this.InitializeComponent();
      }

      private async void button_Click(object sender, RoutedEventArgs e){

        //Add the connection.
         if (this.inventoryService == null) {

            this.inventoryService = new AppServiceConnection();
            this.inventoryService.AppServiceName = "com.microsoft.inventory";
            this.inventoryService.PackageFamilyName =
               "bb1a8478-8005-46869923-e525ceaa26fc_4sz2ag3dcq60a";

            var status = await this.inventoryService.OpenAsync();

            if (status != AppServiceConnectionStatus.Success) {
               button.Content = "Failed to connect";
               return;
            }
         }

        //Call the service.
         int idx = int.Parse(textBox.Text);
         var message = new ValueSet();

         message.Add("Command", "Item");
         message.Add("ID", idx);

         AppServiceResponse response = await
            this.inventoryService.SendMessageAsync(message);
         string result = "";

         if (response.Status == AppServiceResponseStatus.Success) {
           //Get the data  that the service sent  to us.
            if (response.Message["Status"] as string == "OK") {
               result = response.Message["Result"] as string;
            }
         }

         message.Clear();
         message.Add("Command", "Price");
         message.Add("ID", idx);

         response = await this.inventoryService.SendMessageAsync(message);

         if (response.Status == AppServiceResponseStatus.Success){
           //Get the data that the service sent to us.
            if (response.Message["Status"] as string == "OK") {
               result += " : Price = " + "$"+ response.Message["Result"] as string;
            }
         }

         textBlock.Text = result;
      }
   }
}

このアプリケーションを実行するには、ソリューションエクスプローラーで ClientApp プロジェクトをスタートアッププロジェクトに設定し、 Build> Deploy Solutionからこのソリューションを展開する必要があります。

APPサービス

上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。 Appサービスでは、2つのアイテムの情報を追加しました。 したがって、0または1を入力して、これらのアイテムの情報を取得できます。

APPサービス

0を入力してボタンをクリックすると、バックグラウンドタスクとしてAppサービスが実行され、 textblock にアイテム情報が表示されます。