AppServiceConnection 使另一个应用程序能够在后台唤醒你的应用并与之直接通信。
通过引入进程内应用服务,两个正在运行的前景应用程序可以通过应用服务连接进行直接通信。 应用服务现在可以在前台应用程序所在的同一进程中运行,这使得应用之间的通信更加容易,并且不再需要将服务代码分离到单独的项目中。
将进程外模型应用服务转换为进程内模型需要两个更改。 第一个是显著变化。
<Package ... <Applications> <Application Id=... ... EntryPoint="..."> <Extensions> <uap:Extension Category="windows.appService"> <uap:AppService Name="InProcessAppService" /> </uap:Extension> </Extensions> ... </Application> </Applications>
从 EntryPoint
元素中删除 <Extension>
属性,因为现在 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,以检查是否包含 Key
和 Value
字符串。 如果这些值存在,则应用服务会将一对字符串值 Response
和 True
返回到 AppServiceConnection的另一端的应用。
在 创建和使用应用服务详细了解如何连接和通信其他应用。