AppServiceConnection を使用すると、別のアプリケーションがバックグラウンドでアプリを起動し、アプリとの直接通信を開始できます。
インプロセス App Services の導入により、実行中の 2 つのフォアグラウンド アプリケーションは、App Service 接続経由で直接通信を行うことができます。 App Services はフォアグラウンド アプリケーションと同じプロセスで実行できるようになりました。これにより、アプリ間の通信がはるかに簡単になり、サービス コードを別のプロジェクトに分割する必要がなくなります。
アウトプロセス モデル App Service をインプロセス モデルに変換するには、2 つの変更が必要です。 1 つ目はマニフェストの変更です。
<Package ... <Applications> <Application Id=... ... EntryPoint="..."> <Extensions> <uap:Extension Category="windows.appService"> <uap:AppService Name="InProcessAppService" /> </uap:Extension> </Extensions> ... </Application> </Applications>
onBackgroundActivated()
2 つ目の変更は、サービス ロジックを別のバックグラウンド タスク プロジェクトから、OnBackgroundActivated()から呼び出すことができるメソッドに移動することです。
これで、アプリケーションで App Service を直接実行できるようになりました。 たとえば、App.xaml.csでは次のようになります。
[!注] 次のコードは、たとえば 1 (アウトプロセス サービス) で提供されるコードとは異なります。 以下のコードは説明のみを目的として提供されており、例 2 (インプロセス サービス) の一部として使用しないでください。 この記事の例 1 (アウトプロセス サービス) から例 2 (インプロセス サービス) への移行を続行するには、以下の例示コードではなく、例 1 に示されているコードを引き続き使用します。
using Windows.ApplicationModel.AppService;
using Windows.ApplicationModel.Background;
...
sealed partial class App : Application
{
private AppServiceConnection _appServiceConnection;
private BackgroundTaskDeferral _appServiceDeferral;
...
protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
{
base.OnBackgroundActivated(args);
IBackgroundTaskInstance taskInstance = args.TaskInstance;
AppServiceTriggerDetails appService = taskInstance.TriggerDetails as AppServiceTriggerDetails;
_appServiceDeferral = taskInstance.GetDeferral();
taskInstance.Canceled += OnAppServicesCanceled;
_appServiceConnection = appService.AppServiceConnection;
_appServiceConnection.RequestReceived += OnAppServiceRequestReceived;
_appServiceConnection.ServiceClosed += AppServiceConnection_ServiceClosed;
}
private async void OnAppServiceRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
AppServiceDeferral messageDeferral = args.GetDeferral();
ValueSet message = args.Request.Message;
string text = message["Request"] as string;
if ("Value" == text)
{
ValueSet returnMessage = new ValueSet();
returnMessage.Add("Response", "True");
await args.Request.SendResponseAsync(returnMessage);
}
messageDeferral.Complete();
}
private void OnAppServicesCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
_appServiceDeferral.Complete();
}
private void AppServiceConnection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args)
{
_appServiceDeferral.Complete();
}
}
上記のコードでは、OnBackgroundActivated
メソッドが App Service のアクティブ化を処理します。
AppServiceConnection を介した通信に必要なすべてのイベントが登録され、アプリケーション間の通信が完了したときに完了としてマークできるようにタスク遅延オブジェクトが格納されます。
アプリが要求を受け取り、指定された ValueSet を読み取り、Key
文字列と Value
文字列が存在するかどうかを確認します。 存在する場合、App Service は、Response
のもう一方の側にあるアプリに True
と 文字列値のペアを返します。
他のアプリとの接続と通信の詳細については、「App Serviceの作成と使用」を参照してください。