I have a host UWP app which hosts the app service and in its App.xaml.cs I have the code below: private BackgroundTaskDeferral _appServiceDeferral; private AppServiceConnection _appServiceConnection; protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); if (args.TaskInstance.TriggerDetails is AppServiceTriggerDetails) { _appServiceDeferral = args.TaskInstance.GetDeferral(); args.TaskInstance.Canceled += OnAppServicesCanceled; AppServiceTriggerDetails details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails; _appServiceConnection = details.AppServiceConnection; _appServiceConnection.RequestReceived += Connection_RequestReceived; _appServiceConnection.ServiceClosed += AppServiceConnection_ServiceClosed; } }
My host app is a UWP app, and it launches a win32 app at some time, that Win32 is a client app. I have below code for Win32 app:
connection = new AppServiceConnection(); connection.AppServiceName = "MyTestCommunicationService"; connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName; connection.RequestReceived += ClientConnection_RequestReceived; connection.ServiceClosed += Connection_ServiceClosed;
var status = await connection.OpenAsync().AsTask();
In the UWP host app, I can send message to the win32 app:
if (_appServiceConnection!= null)
{
ValueSet valueSet = new ValueSet();
valueSet.Add("Command", dataContent);
AppServiceResponse response = await _appServiceConnection.SendMessageAsync(valueSet);
_isSuccess = response.Status == AppServiceResponseStatus.Success;
}
I see a lot of examples the client sends request to app connection's host app, and host app handles the requests. I wonder is my code the correct way to do the two way communication between the host app and win32 app. I tested the code it is working, but would like to know the best practice about app service connection.
Yes, AppServiceConnection is a two-way communication pipeline. Both sides have an instance of AppServiceConnection that they can use to initiate requests to the other side, as well as to receive requests from the other side.