Friday, November 28, 2014

Background Task in windows phone 8.1

What we had in windows phone 8 ?

In windows phone 8  we had is Period Tasks or Resource Intensive task that could run as background agents , but these has a lot of constraints(CPU time , memory , running time and more), and very little  flexibility to trigger these background agents .

What does windows Phone 8.1 bring to the table ?  

First and the very notable thing is the Triggers, now there is lot more ways you can kick off a background Task , now the developers have lot of options to kick off a background tasks.

Common Trigger Types

  • System Triggers: you can subscribe to some of the events(InternetAvailable,NetworkStateChange,OnlineIdConnectedStateChange,   SmsReceived,TimeZoneChange) raised by OS and trigger your background tasks .
  • Timer Triggers : your app can register a background task that runs every 30 minutes on Windows Phone (** for this trigger you need your app  needs to be on the lock screen).
  • Push Notification Triggers:You can trigger the background task when you receive a raw notification for your app.
  • Maintenance Triggers: This is similar to timer Triggers but this trigger does not have  the prerequisite of the app being placed on the lock screen, instead this will only run when the device is pluggedin  to the power source .
  • Update Task Triggers: Allows you to run some code in the background when the user updates your app to the newer version .
  • DeviceUse Triggers: allows you to access  peripheral devices through background  Tasks .
  • RfcommConnection Triggers:This triggers a background task when ever a Rfcomm connection is made to a device 
  • DeviceConnectionChange Triggers:This Triggers a background task when a Bluetooth device gets connected or disconnected .
  • GattCharacteristicNotificationChange : The Bluetooth device can trigger a background Task by Changing a value for which the app has subscribed for a ValueChanged Event .

How enable your app to run in background

How to create  background task

  1. Add a new project to your solution where you have your foreground app and the project type should be of the type Windows Runtime Component .
  2. Add the above project as a reference to your foreground app(windows phone app) .
  3. In your Windows Runtime Component all you need to do is implement the IBackgroundTask   interface as shown below .

  1. using Windows.ApplicationModel.Background; namespace Tasks { public sealed class ExampleBackgroundTask : IBackgroundTask { public async void Run(IBackgroundTaskInstance taskInstance) { //if you have any async operation then use deferral backgroundtaskdef _def = taskInstance.Getdeferral(); // perform your async task and then call deferral complete _def.Complete(); } } }

 How to register the background task  from your foreground app?

  1. The minimum  object that are need to participate in  registering a background task are

  • TaskEntryPoint :this  will be the fully qualified name of your class name that has implemented the IBackgroundTask Interface
  • TaskName:the name given to your background task
  • TriggerType:lets developer configure how to trigger the background tasks
  • Condition: you can add a system conditions(InternetAvailable ,FreeNetworkAvailable and more  ) along with the trigger option , this condition is an optional parameter.
Below is the generic method which registers the background task and returns a BackgroundTaskRegistration object .

public static async BackgroundTaskRegistration RegisterBackgroundTask(
                                                string taskEntryPoint, 
                                                string name,
                                                IBackgroundTrigger trigger,
                                                IBackgroundCondition condition)
{
    //
    // Check for existing registrations of this background task.
    //

    foreach (var cur in BackgroundTaskRegistration.AllTasks)
    {

        if (cur.Value.Name == taskName)
        {
            // 
            // The task is already registered.
            // 

            return (BackgroundTaskRegistration)(cur.Value);
        }
    }


    //
    // Register the background task.
    //

    var builder = new BackgroundTaskBuilder();

    builder.Name = name;
    builder.TaskEntryPoint = taskEntryPoint;
    builder.SetTrigger(trigger);

    if (condition != null)
    {

        builder.AddCondition(condition);
    }

   // Rumour of a bug which means you have to call this before calling Request...
            BackgroundExecutionManager.RemoveAccess();

            await BackgroundExecutionManager.RequestAccessAsync();

    BackgroundTaskRegistration task = builder.Register();

    return task;
}


3. Declare background task in App Manifest

Update your App Manifest file (Package.appxmanifest) file to declare  all the background tasks used in the app, if this step is not done then the registration will fail.
below is  xml code snippet tgat needs to used in the manifest file 

  <Extensions>
  <Extension Category="windows.backgroundTasks" 

            EntryPoint="Your fully qualified Backgroundclas Name">
    <BackgroundTasks>
      <Task Type="systemEvent" />
    </BackgroundTasks>
  </Extension>
</Extensions>
   
Here is the Sample Code for working with Background task (Download).

0 comments:

Post a Comment