4
votes

This is a weird one.

My Windows Phone 8 app's background agent seems to be updating absolutely fine throughout the day when I'm running a debug build. However, when I change to a release build, it either doesn't run at all or very infrequently. This is for a weather app: my live tile's content should change every hour. I've seen it sometimes update every hour, but then stop for a few hours, and then suddenly start again. At no point does the app's background agent get blocked by the OS either, which suggests to me there's nothing wrong with the background agent or it's just not getting run much/at all.

At the moment, I have debug and release builds of the app on my Lumia 1020 running Windows Phone 8.1. Code-wise they are identical. The debug build is updating every 30 minutes (I know cause of a timestamp on the live tile), whereas the release build has not updated once since it was created 90 minutes ago (but its background agent is still listed as being 'allowed' to run on the Battery Saver app).

Here's the method that creates the agent:

    private void AddAgent(string periodicTaskName)
    {
        periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
        if (periodicTask != null)
        {
            RemoveAgent(periodicTaskName);
        }

        periodicTask = new PeriodicTask(periodicTaskName);
        periodicTask.Description = "LiveTileHelperUpdateTask";

        try
        {
            ScheduledActionService.Add(periodicTask);

            // If debugging is enabled, use LaunchForTest to launch the agent in 5 seconds.
            //#if(DEBUG_AGENT)
               ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(1));
            //#endif
        }
        catch (InvalidOperationException)
        {

        }
        catch (SchedulerServiceException)
        {

        }
    }

And here's the scheduled agent code:

public class ScheduledAgent : ScheduledTaskAgent
{
    /// <remarks>
    /// ScheduledAgent constructor, initializes the UnhandledException handler
    /// </remarks>
    static ScheduledAgent()
    {
        // Subscribe to the managed exception handler
        Deployment.Current.Dispatcher.BeginInvoke(delegate
        {
            Application.Current.UnhandledException += UnhandledException;
        });
    }

    /// Code to execute on Unhandled Exceptions
    private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    {
        if (Debugger.IsAttached)
        {
            // An unhandled exception has occurred; break into the debugger
            Debugger.Break();
        }
    }

    /// <summary>
    /// Agent that runs a scheduled task
    /// </summary>
    /// <param name="task">
    /// The invoked task
    /// </param>
    /// <remarks>
    /// This method is called when a periodic or resource intensive task is invoked
    /// </remarks>
    protected async override void OnInvoke(ScheduledTask task)
    {
        // If the app has not been purchased and trial has expired,
        // don't do anything here.
        if( (bool) IsolatedStorageSettings.ApplicationSettings["TrialExpired"] == true )
            return;

        // Setup view model to get data from.    
        LiveTileViewModel viewModel = new LiveTileViewModel();
        await viewModel.getWeatherForTileLocation();

        // Use a dispatcher because we are NOT on the UI thread!
        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            try
            {                
                RadFlipTileData extendedData = new RadFlipTileData();
                extendedData.IsTransparencySupported = true;

                // Determine which sized tile will be the live tile.
                // Only create a live tile for it due to memory constraints.
                string liveTileSize = IsolatedStorageSettings.ApplicationSettings["LiveTileSize"].ToString();
                switch (liveTileSize)
                {
                    case "SMALL TILE":
                        extendedData.SmallVisualElement = new LiveTileSmall()
                        {
                            Icon = viewModel.Location.Hourly.Data[0].Icon,
                            Temperature = viewModel.Location.Hourly.Data[0].Temperature
                        };
                    break;
                    case "REGULAR TILE":
                        // Code here similar to small tile's
                    break;
                    default:
                        // Code here similar to small tile's
                    break;
                }

                FreeMemory();

                foreach (ShellTile tile in ShellTile.ActiveTiles)
                {
                    LiveTileHelper.UpdateTile(tile, extendedData);
                    break;
                }

                NotifyComplete();
            }
            catch (Exception e)
            {
            }
        }); 
    }
}
}

Anyone got any ideas what might be causing this or had any similar experience where the background agent only works on a debug build?

Thanks for your time.

1
Try logging any errors to a file in the agent. Wrap all of your code in a try catch and log in the catch. Keep it small as you may be running out of memory. Might be good to just log all actions, maybe even setup a service that it can send data to rather than relying on a local text file. You could use Google Analytics for quick debugging.Shawn Kendrot
Please help us in solving this issue. Background task in not running when set debug to release mode. It was working fine in debug mode. And for Windows Phone 8.1 project, we cant upload .xap file which is in built in debug mode. It needs to be set in release mode but when we set in release mode, background task not working.Balasubramani M
I have the same issue.Martin Komischke
I have been getting the similar problem with a WP81 background task. Does the background task continue to run after a reboot of the phone running the debug build?Tim

1 Answers

0
votes

did you try uninstalling the debug build and install the release to verify the background task execution?

And also try to remove the ScheduledActionService.LaunchForTest method call for release build, see the caution section in the docs. In the current code, you specified to trigger test run of background task for every 1 second. There is a limitation, in some cases if this time is below 60 seconds task may not run.