Background Task in Xamarin Forms UWP

This article describes about the Background Task in Xamarin Forms UWP. This background task provides the functionality when the app is suspended (in background) or not running.

Since background task is a platform dependent feature, we must implement it in a platform specific project and make call from Xamarin Forms PCL project with dependency service.

Note: Background task is a light weight and runs based on CPU usage, hence limited to run each task for 30 secs. If there are any operations taking exceeds this time limit, the task gets terminated or cancelled.

In this article, I am going to create a timer task that runs for every 15 mins on a system condition when internet is available. So, this task considers the 15 mins of time interval if the network is available in device. This 15 mins is the minimum time interval for a timer background task to run, so it should be >=15 mins.

Create a Xamarin forms project and add a project Windows Runtime Component for UWP project for background task implementation.

Create a class to implement the IBackgroundTask. The Run method is a required entry point that will be called when the specified event is triggered; this method is required in every background task.

public sealed class SystemBackgroundTask : IBackgroundTask
    {
         private BackgroundTaskDeferral deferral = null;
        private IBackgroundTaskInstance backgroundtaskInstance = null;

        public void Run(IBackgroundTaskInstance taskInstance)
         {
             taskInstance.Canceled += this.TaskInstanceCanceled;
             this.deferral = taskInstance.GetDeferral();
             this.ShowToast("Running Background Task");
            this.deferral.Complete();
        }

         private void TaskInstanceCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
             this.deferral.Complete();
        }

         private void ShowToast(string message)
        {
            try
            {
                ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
                XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
                XmlNodeList textElements = toastXml.GetElementsByTagName("text");
                 textElements[0].AppendChild(toastXml.CreateTextNode("chat message:"));
                 textElements[1].AppendChild(toastXml.CreateTextNode(message));
                 ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
            }
            catch (Exception)
             {
                 // ignored
            }
        }
    }

From above, displaying the Toast notification in Run method.   If you run any asynchronous code in your background task, then your background task needs to use a deferral. If you don't use a deferral, then the background task process can terminate unexpectedly if the Run method completes before your asynchronous method call has completed.  Request the deferral in the Run method before calling the asynchronous method. Save the deferral to a global variable so it can be accessed from the asynchronous method. Declare the deferral complete after the asynchronous code completes.

Register the Background task in UWP project as below. Before registering, ensure to check whether the task has been already registered.

[assembly: Xamarin.Forms.Dependency(typeof(BackgroundService))]
namespace BackgroundXamarinForms.UWP.Renderers
{
    using Windows.ApplicationModel.Background;

    public class BackgroundService : IBackgroundService
    {
         private const string TaskEntryPoint = "BackgroundTasksUWP.SystemBackgroundTask";

        private const string TaskName = "TimerBackgroundTask";

        public async Task RegisterBackgroundTask()
        {
            foreach (var task in BackgroundTaskRegistration.AllTasks)
             {
                 if (task.Value != null && task.Value.Name.Equals(TaskName))
                 {
                      task.Value.Unregister(true);
                }
            }

            var builder = new BackgroundTaskBuilder();

            await BackgroundExecutionManager.RequestAccessAsync();

            builder.Name = TaskName;
            builder.TaskEntryPoint = TaskEntryPoint;
            var trriger = new TimeTrigger(15, false);
            builder.SetTrigger(trriger);
            builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));

             // builder.CancelOnConditionLoss = true;
            builder.Register();
        }
    }
}

From above, registering the background task by defining the task entry point and background task trigger and system conditions.

Add the background task configuration changes to manifest file, under Declarations tab select background task and add properties as below.
      
Now call the background task register method from PCL project as below.

var service = DependencyService.Get<IBackgroundService>();

 if (service != null)
  {
      await service.RegisterBackgroundTask();
  }

If you want to test the background task in debug mode, then select the background task from life cycle events while running the app.
Example of toast message when the app is inactive.


Please refer link to know further about background tasks in UWP.

Download the working sample.

By Siva Jagan Dhulipalla   Popularity  (204 Views)