简体   繁体   中英

ScheduledTaskAgent issue in updating WP8 app tiles programatically

I am recently working in a Windows Phone 8 app that update tiles in background. I followed this http://jeffblankenburgdotcom.wordpress.com/2011/11/25/31-days-of-mango-day-25-background-agents/ tutorial to make my work done. I followed every steps, but its putting the tile first but it does not updated the next tile after 60seconds in background. You can download the solution file here https://onedrive.live.com/?cid=843581c79c017ebc&id=843581C79C017EBC%21149&ithint=file,.rar&authkey=!ABbazYty8Rw7a_A

MainPage.xaml.cs is

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 is

#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);
            }
        } 
    }
}

Note : I have put the reference.

在MainPage.xaml.cs文件顶部添加#define DEBUG_AGENT行之后,该文件将#define DEBUG_AGENT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM