计划以更新WP8应用程序磁贴的计划任务代理问题

时间:2014-03-15 05:38:41

标签: c# windows-phone-8 scheduled-tasks

我最近在Windows Phone 8应用程序中工作,在后台更新磁贴。我按照这个http://jeffblankenburgdotcom.wordpress.com/2011/11/25/31-days-of-mango-day-25-background-agents/教程完成了我的工作。我按照每个步骤进行操作,但是它将瓷砖放在第一位,但在后台60秒后它没有更新下一个瓷砖。您可以在此处下载解决方案文件https://onedrive.live.com/?cid=843581c79c017ebc&id=843581C79C017EBC%21149&ithint=file,.rar&authkey=!ABbazYty8Rw7a_A

MainPage.xaml.cs是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using BackgroundAgentTileTest.Resources;
using Microsoft.Phone.Scheduler;

namespace BackgroundAgentTileTest
{
    public partial class MainPage : PhoneApplicationPage
    {
        PeriodicTask periodicTask;
        string periodicTaskName = "PeriodicAgent";
        bool agentsAreEnabled = true;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            agentsAreEnabled = true;

            // Obtain a reference to the period task, if one exists
            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            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 = "This demonstrates a periodic task.";

            // 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.
#if(DEBUG_AGENT)
                ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(10));
#endif
            }
            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;

                }

                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.

                }

            }
            catch (SchedulerServiceException)
            {
                // No user action required.  
            }
        }

        private void RemoveAgent(string periodicTaskName)
        {

            try
            {
                ScheduledActionService.Remove(periodicTaskName);
            }
            catch (Exception)
            {
            }
        }
    }
}

ScheduledAgent.cs是

#define DEBUG_AGENT

using System.Diagnostics;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using System;
using System.Linq;

namespace ScheduledTaskAgent1
{
    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 override void OnInvoke(ScheduledTask task)
        {
            //TODO: Add code to perform your task in background
            //UpdateAppTile(GetLastUpdatedTimeMessage()); 
            StandardTileData data = new StandardTileData

            {

                Title = "My tile!",

                Count = 10, // I Need To Get This Counter From Isolated Storage Or My Other main Project

                BackgroundImage = new Uri("/Background.png", UriKind.RelativeOrAbsolute),

                BackTitle = "This is the back",

                BackContent = DateTime.Now.ToString(),

                BackBackgroundImage = new Uri("/Background.png", UriKind.RelativeOrAbsolute)
            };

            ShellTile.ActiveTiles.First().Update(data);
            // If debugging is enabled, launch the agent again in one minute.
#if DEBUG_AGENT
    ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));
#endif
            NotifyComplete();
        }

        private string GetLastUpdatedTimeMessage()
        {
            return string.Format("Last Updated: {0}", DateTime.Now);
        }

        private void UpdateAppTile(string message)
        {
            ShellTile appTile = ShellTile.ActiveTiles.First();
            if (appTile != null)
            {
                StandardTileData tileData = new StandardTileData
                {
                    BackContent = message
                };
                appTile.Update(tileData);
            }
        } 
    }
}

注意:我已经把参考文献。

1 个答案:

答案 0 :(得分:0)

在MainPage.xaml.cs文件的顶部添加#define DEBUG_AGENT行后,它可以正常工作。