轉換應用程式服務,以便與其主機應用程式在相同處理序中執行

AppServiceConnection 讓另一個應用程式能夠在背景喚醒您的應用程式並啟動與其進行直接通訊。

透過引進同程序應用程式服務,兩個執行的前景應用程式可以透過 App Service 連線直接進行通訊。 App Services 現在可以在與前景應用程式相同的程序中執行,讓應用程式之間的通訊變得更容易,而且不需要將服務程式碼分隔成個別專案。

將跨程序模型應用程式服務轉換成程序內模型需要兩個變更。 第一個是指令清單變更。

<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:

[!NOTE] 下面的程式碼與範例 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 另一端的應用程式。

在建立和使用應用程式服務中深入瞭解如何連線及與其他應用程式通訊。