Search code examples
windows-phone-7live-tile

Background agent task is never executed in Mango


I have a background agent that i would like to be executed in Mango for updating the live tile. The problem is that it is never executed. Here is the code that i used:

//start background agent 
PeriodicTask periodicTask = new PeriodicTask("BruceWpAgent");

periodicTask.Description = "BruceWp periodic live task";
periodicTask.ExpirationTime = System.DateTime.Now.AddDays(10);

// If the agent is already registered with the system,
if (ScheduledActionService.Find(periodicTask.Name) != null)
{
     ScheduledActionService.Remove("BruceWpAgent");
}

ScheduledActionService.Add(periodicTask);

I've found my app name between that Apps that use background jobs but the task is never invoked. What am i doing wrong?


Solution

  • This code may help you..

    string periodicTaskName = "PeriodicAgent";      
        public bool agentsAreEnabled = true;
        private void StartBackgroundAgent()
        {
            // Variable for tracking enabled status of background agents for this app.
            agentsAreEnabled = true;
            // Obtain a reference to the period task, if one exists
            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
    
            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule
            if (periodicTask != null)
            {
                RemoveAgent(periodicTaskName);
            }
    
            periodicTask = new PeriodicTask(periodicTaskName);
    
            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            periodicTask.Description = "Task to update the Economic times tile.";
    
            // Place the call to Add in a try block in case the user has disabled agents
            try
            {
                ScheduledActionService.Add(periodicTask);
                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
    
                ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromMinutes(2));
    
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                    agentsAreEnabled = false;
                }
            }
        }