将应用服务转换为与其主机应用在同一个进程中运行

AppServiceConnection 使其他应用程序可以在后台唤醒你的应用,并建立与它的直接通信。

引入进程内应用服务后,两个正在运行的前台应用程序可通过应用服务连接建立直接通信。 应用服务现在可以在与前台应用程序相同的进程中运行,这简化了应用之间的通信,也无需将服务代码分离到独立项目。

将进程外模型的应用服务转换为进程内模型需要两项更改。 第一项是清单更改。

<Package
   ...
  <Applications>
      <Application Id=...
          ...
          EntryPoint="...">
          <Extensions>
              <uap:Extension Category="windows.appService">
                  <uap:AppService Name="InProcessAppService" />
              </uap:Extension>
          </Extensions>
          ...
      </Application>
  </Applications>

<Extension> 元素中删除 EntryPoint 属性,因为现在 OnBackgroundActivated() 是调用应用服务时将使用的入口点。

第二项更改是将服务逻辑从其单独的后台任务项目移动至可从 OnBackgroundActivated() 调用的方法。

此时,应用程序可直接运行应用服务。 例如,在 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 方法处理应用服务激活。 通过 AppServiceConnection 进行通信所需的所有事件均已注册,并且任务延迟对象已存储,以便在应用程序之间的通信完成时可标记为“完成”。

在应用收到请求并读取所提供的 ValueSet 时,查看是否存在 KeyValue 字符串。 如果它们存在,则应用服务会将一对 ResponseTrue 字符串值返回给 AppServiceConnection 另一端的应用。

请在创建和使用应用服务中了解关于连接和与其他应用通信的详细信息。