Background Task In Universal Windows Program - Part Five

Before reading this article, please go through the following articles,

Introduction

Universal Windows Program App Service is like web services. One app can communicate to another app to get the information even if one of the apps is not running in the foreground.

Universal Windows Program App Services

Universal Windows Program App Service runs Command style. The app sends the command to App Service. Based on that command, the App service sends the response to the app and the app that is running in the Background Task.

Appservice Diagram

Diagram

The main application is hosted in the App Services as background task. Then, both the applications communicate to app services.

App Service Implementation.

  1. Create a Windows Runtime component.

    Windows Runtime component

  2. Implement IBackgroundTask & Run Method.
    1. public sealed class UwpAppService : IBackgroundTask  
    2. {  
    3. public void Run(IBackgroundTaskInstance taskInstance)  
    4. {  
    5.   
    6. }  
    7. }  
  3. Create AppServiceConnection connection & implement the RequestReceived call back function.
    1. private AppServiceConnection _appServiceConnection;  
    2. public void Run(IBackgroundTaskInstance taskInstance)   
    3. {  
    4.     _bgTaskDeferral = taskInstance.GetDeferral();  
    5.     taskInstance.Canceled += TaskInstanceCancel;  
    6.     var triggerAppService = taskInstance.TriggerDetails as AppServiceTriggerDetails;  
    7.     if (triggerAppService == nullreturn;  
    8.     _appServiceConnection = triggerAppService.AppServiceConnection;  
    9.     _appServiceConnection.RequestReceived += AppServiceRequestReceived;  
    10. }  
    Note:

    a) var triggerAppService = taskInstance.TriggerDetails as AppServiceTriggerDetails

    Convert TriggerDetails in AppServiceTriggerDetails. This is needed because in the same background process, we can implement another trigger also. ex: TimeZoneChange event that converts into the AppServiceTriggerDetails.

    b) Getting the Connection object and implement RequestReceived call back.

    _appServiceConnection = triggerAppService.AppServiceConnection;
    _appServiceConnection.RequestReceived += AppServiceRequestReceived;

    RequestReceived: This callback is used to handle the get Request from the app and respond back.
    1. private async void AppServiceRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)  
    2. {  
    3. var serviceMsg = args.GetDeferral();  
    4. serviceMsg.Complete();   
    5. }  
  4. Appservice component is ready.

Add Appservice component into the main application.

  1. Create a blank application.

    blank application

  2. Add Appservice into the Package.appxmanifest file.

    Appservice

    Name properties: com.microsoft.BGAppService (if service is running in one of the domains Microsoft has recommended, use the domain name in reverse order).

  3. Build the Project & Run it. Appservice is ready and is running.

Communication to the Appservice (Main Application communicates to the Appservice).

  1. Create an Appservice Connection object.
    1. AppServiceConnection _appService;  
    2. _appService = new AppServiceConnection  
    3. {  
    4. AppServiceName = "com.microsoft.BgAppService",  
    5. PackageFamilyName = "69533c06-5ce5-4f1a-93fe-151ca737537a_kz0gnaa3h8516"  
    6. };  
    Note:

    Create

    For creating Appservice connection, AppserviceName and PackageFamilyName are required. 

    a. AppserviceName: Represents the name of the service which has been declared in the Package.appxmanifest file.

    b. PackageFamilyName: Main application package name; indicates which application hosts the Appservice task. PackageFamilyName can be found in the Package.appxmanifest file or read the packageName in runtime.

    string packageName = Package.Current.Id.FamilyName;

    PackageFamilyName

  2. Once connection object has been created. Now, open the connection.
    _appStatus = await _appService.OpenAsync();

    It will return the AppServiceConnectionStatus, if connection is successful, send the request to the Appservice. Otherwise, don’t.

    AppServiceConnectionStatus

  3. await _appService.SendMessageAsync(responseUpdate);

Command to understand the Client and Appservice.

Until this, we have created Appservice & Connection object in the UI side. Now, we will see how to implement the communication part.

ValueSet

 ValueSet is a collection of key and value relationships.  The Key is a string and Value is an object.

This ValueSet is used for communication purposes to understand the Appservice and UI. Generally, each request contains two Keysets.

  1. First Keyset contains the “Command”,  A command can be like anything -  get, set, read, or write.
    1. var responseUpdate = new ValueSet();  
    2. responseUpdate.Add("Command""set");  
  2. The second Keyset contains the command value.
    1. responseUpdate.Add("serverMsg", sendMsg);  
    2.   
    3. //UI prepare the command and send to the service   
  3. await _appService.SendMessageAsync(responseUpdate);

Handling the Command in Service side

  1. private async void AppServiceRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) {}  
  2. AppServiceRequestReceivedEventArgs  
  3. AppServiceRequestReceivedEventArgs it contains the command information, which send by client  
  4. AppServiceRequestReceivedEventArgs.Request.Message, here the read the information from the client.  
  5. var storeData = args.Request.Message;  
  6. string command = storeData["Command"as string;  
Check the command and process it. 

Once the process has been done, prepare the response to the client who has requested for the service. Prepare the response by creating the ValueSet collection.
  1. ValueSet returnData = new ValueSet();  
  2. returnData.Add("Result""OK");  
  3. await args.Request.SendResponseAsync(returnData);  
In my next article, we will see the example of the communication between the two apps.


Similar Articles